Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping two (or more) arrays into one with underscore.js

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?

like image 859
David Pardo Avatar asked Feb 27 '13 09:02

David Pardo


3 Answers

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]
like image 74
Daniel Margol Avatar answered Nov 01 '22 03:11

Daniel Margol


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);
});
like image 21
Bergi Avatar answered Nov 01 '22 04:11

Bergi


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]
like image 4
elclanrs Avatar answered Nov 01 '22 02:11

elclanrs