Changed all loops to Array.prototype.reduce()