Sum two arrays in single iteration
Solution 1:
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]
Solution 2:
Here is a generic solution for N arrays of possibly different lengths.
It uses Array.prototype.reduce(), Array.prototype.map(), Math.max() and Array.from():
function sumArrays(...arrays) {
const n = arrays.reduce((max, xs) => Math.max(max, xs.length), 0);
const result = Array.from({ length: n });
return result.map((_, i) => arrays.map(xs => xs[i] || 0).reduce((sum, x) => sum + x, 0));
}
console.log(...sumArrays([0, 1, 2], [1, 2, 3, 4], [1, 2])); // 2 5 5 4
Solution 3:
var arr = [1,2,3,4];
var arr2 = [1,1,1,2];
var squares = arr.map((a, i) => a + arr2[i]);
console.log(squares);
Solution 4:
Below example will work even with length variation and few more use cases. check out. you can do prototyping as well if you needed.
function sumArray(a, b) {
var c = [];
for (var i = 0; i < Math.max(a.length, b.length); i++) {
c.push((a[i] || 0) + (b[i] || 0));
}
return c;
}
// First Use Case.
var a = [1, 2, 3, 4];
var b = [1, 2, 3, 4];
console.log( sumArray(a, b) );
// Second Use Case with different Length.
var a = [1, 2, 3, 4];
var b = [1, 2, 3, 4, 5];
console.log( sumArray(a, b) );
// Third Use Case with undefined values and invalid length.
var a = [1, 2, 3, 4];
var b = [];
b[1] = 2;
b[3] = 4;
b[9] = 9;
console.log( sumArray(a, b) );
Solution 5:
Just merge Popovich and twalters's answer.
Array.prototype.SumArray = function (arr) {
var sum = this.map(function (num, idx) {
return num + arr[idx];
});
return sum;
}
var array1 = [1,2,3,4];
var array2 = [5,6,7,8];
var sum = array1.SumArray(array2);
console.log(sum); // [6,8,10,12]