Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Sum two arrays in single iteration

I want to sum each value of an array of numbers with its corresponding value in a different array of numbers, and I want to do this without looping through each individual value.

So:

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

I'd love to do it in one fell swoop, instead of doing this:

for(var i = 0; i < array1.length; i++){    sum.push(array1[i] + array2[i]); } 

Can anyone think of a way? I'm pretty stumped.

like image 407
TheNovice Avatar asked Jun 07 '14 06:06

TheNovice


People also ask

How do you sum two arrays?

The idea is to start traversing both the array simultaneously from the end until we reach the 0th index of either of the array. While traversing each elements of array, add element of both the array and carry from the previous sum. Now store the unit digit of the sum and forward carry for the next index sum.

How do you sum up an array in JavaScript?

To get the sum of an array of numbers: Use the Array. reduce() method to iterate over the array. Set the initial value in the reduce method to 0 . On each iteration, return the sum of the accumulated value and the current number.

What happens if we add two arrays in JavaScript?

In summary, the addition of arrays causes them to be coerced into strings, which does that by joining the elements of the arrays in a comma-separated string and then string-concatenating the joined strings.

Is there a sum () in JavaScript?

sum() function in D3. js is used to return the sum of the given array's elements. If the array is empty then it returns 0. Parameters: This function accepts a parameters Array which is an array of elements whose sum are to be calculated.


2 Answers

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] 
like image 146
twalters Avatar answered Sep 20 '22 21:09

twalters


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
like image 35
jo_va Avatar answered Sep 22 '22 21:09

jo_va