gpt4 book ai didi

javascript - 创建一个由另一个二维数组累积组成的二维数组

转载 作者:行者123 更新时间:2023-11-30 09:46:29 25 4
gpt4 key购买 nike

我有一个这样的数组:[[0, 50], [1, 40], [2, 30], [3, 20], [5, 10]]

我想累加第二个值:[[0, 50], [1, 90], [2, 120], [3, 140], [5, 150]]

我尝试了下面的代码部分,它适用于一维数组,但不适用于二维数组。是否可以通过使用 reduce 函数来累积它?或者有不同的方法吗?

var array1 = [[0, 50], [1, 40], [2, 30], [3, 20], [5, 10]];
var newArray1 = [];

array1.reduce(
function (previousValue, currentValue, currentIndex) {
return newArray1[currentIndex] = [currentIndex, (previousValue[1] + currentValue[1])];
}, 0
);

最佳答案

您可以使用 map()带有可选的 thisArg 参数

var array1 = [[0, 50], [1, 40], [2, 30], [3, 20], [5, 10]];

var result = array1.map(function(e) {
this.num = (this.num || 0) + e[1];
return [e[0], this.num];
}, {});

console.log(result);

关于javascript - 创建一个由另一个二维数组累积组成的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38765253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com