Refactored code to use for loops instead of forEachs, as the forEach is 95-98% slower than for loops. (tested in http://jsperf.com/iterationsxx)