使用 underscore.js 将两个(或更多)数组映射为一个 [英] Mapping two (or more) arrays into one with underscore.js

查看:27
本文介绍了使用 underscore.js 将两个(或更多)数组映射为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要按元素添加几个数组.也就是说,我有几个等长的数组,我只需要一个元素数量与输入总和相同的数组.Underscore 具有将所有元素折叠为一个并使用函数映射每个元素的方法,但我找不到任何方法将两个数组分段组合.

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.

如果我的原始数组是 [1,2,3,4,5,6], [1,1,1,1,1,1][2,2,2,2,2,2] 结果应该是[4,5,6,7,8,9].

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].

我知道我可以通过迭代数组来完成,但想知道使用 underscore.js 函数是否会更容易/更快.我可以做吗?怎么样?

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?

推荐答案

更容易是,更快不是.要模拟 zipWith,您可以将 zip 与 sum-reduce:

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

这篇关于使用 underscore.js 将两个(或更多)数组映射为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆