Abstracting repetitious for loop into a function (needs a better name though)