gpt4 book ai didi

javascript - 如何找到数组中每个子数组的最大值,然后将它们分组到一个新数组中

转载 作者:行者123 更新时间:2023-11-30 07:51:59 24 4
gpt4 key购买 nike

如何找到数组中每个子数组的最大值,然后将它们分组到一个新数组中?

例如:

[1, 2, [3, 4]]//return[2, 4]
[1000, [1001, 857, 1]]//return[1000, 1001]
[[4, 5, 1, 3], 2 , 6 ,[1000, [1001, 857, 1]]]//return[5, 6, 1000, 1001]

最佳答案

试试这个:

const a = [1, 2, [3, 4]];
const b = [1000, [1001, 857, 1]];
const c = [[4, 5, 1, 3], 2 , 6 ,[1000, [1001, 857, 1]]];

const max = (array) => {

const a1 = [];
const a2 = [];

array.forEach((a) => (a instanceof Array) ? a1.push(max(a)) : a2.push(a));

a1.push(Math.max(...a2));

return a1.reduce((acc, val) => acc.concat(val), []).sort((a, b) => a - b);
};

console.log(max(a));
console.log(max(b));
console.log(max(c));

关于javascript - 如何找到数组中每个子数组的最大值,然后将它们分组到一个新数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51082106/

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