Converted array.reduce to a simple for loop due to speed concerns