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?
Easier yes, faster no. To emulate a
zipWith
, you can combine azip
with a sum-reduce
:I don't think it would be easier with underscore. Here's two options:
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)
You can use zip in conjunction with map and reduce: Not tested but something like this might work
Using Lodash 4: