Updated method flatten to use each instead of for loop