refactors loop to reduce