gpt4 book ai didi

javascript - 映射二维数组的元素,忽略最后一个子数组

转载 作者:行者123 更新时间:2023-12-03 02:24:50 25 4
gpt4 key购买 nike

假设有这个矩阵:

myArray = [["a", 6, 5.54, "b"],
["xxx", 65.5, 45],
[343, "abc", 0.09]];

我的目标是计算每个子数组的总和,但忽略最后一个子数组,在本例中为[343, "abc", 0.09]。另外,忽略字符串值。

我设法对所有子数组执行此操作,它看起来像这样:

myArray = [["a", 6, 5.54, "b"],
["xxx", 65.5, 45],
[343, "abc", 0.09]];

result = myArray.map(a => a.reduce((s, v) => s + (+v || 0), 0));
console.log(result)

不知道要添加哪个条件才能忽略最后一个子数组。

有什么想法吗?

最佳答案

使用函数slice(0, -1)

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

Second param: A negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence.

var myArray = [
["a", 6, 5.54, "b"],
["xxx", 65.5, 45],
[343, "abc", 0.09]
];

var result = myArray.slice(0, -1).map(a => a.reduce((s, v) => s + (+v || 0), 0));

console.log(result);

关于javascript - 映射二维数组的元素,忽略最后一个子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48991906/

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