-1

How to add value of equals index of an array to another?

I know I can do something like this:

var i = 0,
    a = [1, 2, 3],
    b = [4, 5, 6],
    total = [];

while (i < a.length) {
    total[i] = a[i] + b[i];
    i = i + 1;
}

console.log(total); //[5, 7, 9]

But is there a standard or faster way of doing this?

(In my specific case, a.length === b.length in all cases).

DrakaSAN
  • 7,673
  • 7
  • 52
  • 94

2 Answers2

1

You might find this a bit more compact:

a.map(function(v, i) { return v + b[i]; })

It will be even more compact in ES6:

a.map((v, i) => v + b[i])

We can write our own version of map which loops over two arrays in parallel:

function mapTwo(arr1, arr2, fn, ctxt) {
    return arr1.map(function(v, i) {
        return fn.call(ctxt, v, arr2[i], i);
    };
}

Now we can solve the original problem with

mapTwo(a, b, function(v1, v2) { return v1 + v2; }))

Or, if we really wanted to, let's write a map which iterates over many arrays. It will invoke the callback with an array of values, one from each input array.

function mapMany(arrays, fn, ctxt) {
    fn = fn.bind(ctxt);
    return arrays[0].map(function(_, i) {
        return fn(arrays.map(function(array) { return array[i]; }), i);
    };
}

Now we can do

mapMany([a,b], sum);

where sum is

function sum(values) {
    return values.reduce(function(result, val) { return result+val; });
}

We could also write a more general function, called zip, which combines the elements at each index in the input arrays into an array, so returning an array of arrays. We will now handle the case where the arrays are of different length;

function zip(arrays) {
    var result = [],
        max = Math.max.apply(0, arrays.map(function(array) { return array.length; }));
    for (var i=0; i<max; i++) {
        result.push(arrays.map(function(array) { return array[i]; });
    } 
    return result;
}

Now we can create the pair-wise sums with

zip([a,b]).map(sum)
-1

No, there is not really a 'standard' way of doing this. Maybe libraries as LoDash can help you out here. Specifically take a look at the .zip() function

Bas Slagter
  • 9,831
  • 7
  • 47
  • 78