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.
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.
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.
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.
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.
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With