Refactored code to eliminate one forEach loop