Sum two arrays in single iteration

I know this is an old question but I was just discussing this with someone and we came up with another solution. You still need a loop but you can accomplish this with the Array.prototype.map().

var array1 = [1,2,3,4];
var array2 = [5,6,7,8];

var sum = array1.map(function (num, idx) {
  return num + array2[idx];
}); // [6,8,10,12]

Leave a Comment