Refactored code using each loops to condense