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)