TheNovice TheNovice - 4 months ago 19
Javascript Question

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];


But 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.

Answer

You can't avoid the loop, but you can do this once and add a function to all Array objects using Array.prototype.

Here's and example:

// Add a SumArray method to all arrays by expanding the Array prototype(do this once in a general place)
Array.prototype.SumArray = function (arr) {
    var sum = [];
    if (arr != null && this.length == arr.length) {
        for (var i = 0; i < arr.length; i++) {
            sum.push(this[i] + arr[i]);
        }
    }

    return sum;
}

// here's your code
var array1 = [1, 2, 3, 4];
var array2 = [5, 6, 7, 8];
var sum = array1.SumArray(array2);
console.log(sum); // [6,8,10,12]

Here's your Fiddle.