我有一个二维数组,其结构如下:
我想将值相对于它们的索引相加。(-10000 + 100 + 100 + -100)。然后将它们存储在一个单独的数组中,如下所示:
[[500], [-10100], [9000], [18000], [18000]]
Run Code Online (Sandbox Code Playgroud)
我想我必须使用map和reduce来实现这一目标,但是我运气并不好。
这是我目前拥有的:
for (var i=1; i<totals.length; i++) {
for (var z=0; z<totals[i].length; z++) {
console.log(totals[i][z] = totals[i-1][z] + totals[i][z]);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这似乎输出以下内容:
如果有人可以将我推向正确的方向,那就太好了。
使用Array.prototype.map()和Array.prototype.reduce():
const arrays = [
[500],
[-10000, 100, 100, -100],
[9000],
[9000, 9000],
[9000, 9000]
];
const result = arrays.map(xs => xs.reduce((sum, x) => sum + x, 0));
console.log(JSON.stringify(result));Run Code Online (Sandbox Code Playgroud)
如果希望将每个和都放在数组中,只需将其放在方括号中即可:
const arrays = [
[500],
[-10000, 100, 100, -100],
[9000],
[9000, 9000],
[9000, 9000]
];
const result = arrays.map(xs => [xs.reduce((sum, x) => sum + x, 0)]);
console.log(JSON.stringify(result));Run Code Online (Sandbox Code Playgroud)