简体   繁体   English

使用underscore.js将两个(或更多)数组映射到一个数组

[英]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. Underscore有方法将所有元素折叠成一个并使用函数映射每个元素,但我找不到任何方法将两个数组合并。

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] . 如果我的原始数组是[1,2,3,4,5,6][1,1,1,1,1,1][2,2,2,2,2,2] ,结果应该是[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. 我知道我可以通过迭代数组来做到这一点,但想知道使用underscore.js函数是否更容易/更快。 Can I do it? 我可以做吗? How? 怎么样?

Easier yes, faster no. 更简单,更快,没有。 To emulate a zipWith , you can combine a zip with a sum- reduce : 为了模拟zipWith ,可以将结合zip与求和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]

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. 您可以使用lodash( https://lodash.com/ )而不是下划线,它具有非常酷的zipWith( https://lodash.com/docs#zipWith )运算符,其工作方式类似于下面的示例。 (note _.add is also a lodash math function) (注意_.add也是一个lodash数学函数)

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]

您可以将zip与map结合使用并减少:未经测试但是这样的东西可能有效

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

Using Lodash 4 : 使用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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM