refactoring for loops for faster functionality