我有一个多维数组,如下所示:
[
["1","2","3","4"],
["1","2","3","4"],
["1","2","3","4"],
["1","2","3","4"]
]
我希望通过在索引中添加数组的值将所有内容组合到一个数组中。
预期结果:
[4,8,12,16] //(adding the 4 array values with appropriate index)
我看到Lodash有一个方法_.zip
,但是它不接受数组数组作为输入来给出正确的值。有没有容易实现的目标?
答案 0 :(得分:3)
如果_.zip
不接受数组数组作为输入,那么有一个技术可以实现它。 _.zip.apply(null, array)
。
可以像下面这样完成。 (请注意您的底层元素是字符串,因此还有一个步骤可将它们转换为数字。)
var data =[
["1","2","3","4"],
["1","2","3","4"],
["1","2","3","4"],
["1","2","3","4"]
];
var result = _.map(_.zip.apply(null, data), function (n) {
return _.sum(_.map(n, function(x) { return +x; }));
});
console.log(result);
答案 1 :(得分:2)
我正在解释你的问题如下:将数组中的每个元素映射到它的长度加上前一个元素的值。这是你可以做到的一种方式。
x = [
["1","2","3","4"],
["1","2","3","4"],
["1","2","3","4"],
["1","2","3","4"]
]
result = x.map(function(a) {
return a.length;
}
for (i = 1; i < result.length; ++i) {
result[i] += result[i - 1];
}