Refactoring ugly each loops with if statements into map operations