Mapping two (or more) arrays into one with undersc

2019-04-20 18:14发布

问题:

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?

回答1:

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);
});


回答2:

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]


回答3:

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]


回答4:

You can use zip in conjunction with map and reduce: Not tested but something like this might work

var result = _.map(_.zip(array1, array2, array3),function(zipped){return _.reduce(zipped,  function(memo, num){ return memo + num; }, 0)});


回答5:

Using Lodash 4:

var arrays = [
  [1, 2, 3, 4, 5, 6],
  [1, 1, 1, 1, 1, 1],
  [2, 2, 2, 2, 2, 2]
];

var result = _.map(_.unzip(arrays), _.sum);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>