如何将数组数组中相同索引处的元素加到一个数组中? [英] How to sum elements at the same index in array of arrays into a single array?
问题描述
假设我有一个数组数组,如下所示:
Let's say that I have an array of arrays, like so:
[
[0, 1, 3],
[2, 4, 6],
[5, 5, 7],
[10, 0, 3]
]
如何生成一个新数组,该数组在javascript中对内部数组的每个位置的所有值求和?在这种情况下,结果将是:[17,19,19]。无论内部数组的长度如何,我都需要能够提供一个有效的解决方案。我认为这可以使用map和for-of的一些组合,或者可能减少,但我不能完全围绕它。我已经搜索但找不到任何与此匹配的例子。
How do I generate a new array that sums all of the values at each position of the inner arrays in javascript? In this case, the result would be: [17, 10, 19]. I need to be able to have a solution that works regardless of the length of the inner arrays. I think that this is possible using some combination of map and for-of, or possibly reduce, but I can't quite wrap my head around it. I've searched but can't find any examples that quite match this one.
推荐答案
你可以使用 Array.prototype.reduce()
与 Array.prototype.forEach()
。
You can use Array.prototype.reduce()
in combination with Array.prototype.forEach()
.
var array = [
[0, 1, 3],
[2, 4, 6],
[5, 5, 7],
[10, 0, 3]
],
result = array.reduce(function (r, a) {
a.forEach(function (b, i) {
r[i] = (r[i] || 0) + b;
});
return r;
}, []);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
更新,通过采用减少数组的地图来缩短方法。
Update, a shorter approach by taking a map for reducing the array.
var array = [[0, 1, 3], [2, 4, 6], [5, 5, 7], [10, 0, 3]],
result = array.reduce((r, a) => a.map((b, i) => (r[i] || 0) + b), []);
console.log(result);
这篇关于如何将数组数组中相同索引处的元素加到一个数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!