I'd need to add element-wise several arrays. That is, I have several arrays of equal lenght, and I'd need just one with the same number of elements that are the sum of the inputs. Underscore has methods to fold all elements into one and to map every element using a function, but I can't find any way to combine two arrays piece wise.
If my original arrays were [1,2,3,4,5,6]
, [1,1,1,1,1,1]
and [2,2,2,2,2,2]
the result should be [4,5,6,7,8,9]
.
I know I can do it by iterating over the arrays, but wonder if it would be easier/faster using underscore.js functions. Can I do it? How?
You could use lodash (https://lodash.com/) instead of underscore which has a pretty cool zipWith (https://lodash.com/docs#zipWith) operator that would work like the example below. (note _.add is also a lodash math function)
var a = [1,2,3,4,5,6]
, b = [1,1,1,1,1,1]
, c = [2,2,2,2,2,2];
var result = _.zipWith(a, b, c, _.add);
// result = [4, 5, 6, 7, 8, 9]
Easier yes, faster no. To emulate a zipWith
, you can combine a zip
with a sum-reduce
:
var arrays = [[1,2,3,4,5,6], [1,1,1,1,1,1], [2,2,2,2,2,2]];
_.map(_.zip.apply(_, arrays), function(pieces) {
return _.reduce(pieces, function(m, p) {return m+p;}, 0);
});
I don't think it would be easier with underscore. Here's two options:
var a = [1,2,3,4,5,6]
, b = [1,1,1,1,1,1]
, c = [2,2,2,2,2,2];
var result = a.map(function(_,i) {
return a[i] + b[i] + c[i];
});
// OR
var result = [];
for (var i = 0; i < a.length; i++) {
result.push(a[i] + b[i] + c[i]);
}
console.log(result); //=> [4,5,6,7,8,9]
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