gpt4 book ai didi

javascript - 查找数组数组中最长数组的索引

转载 作者:可可西里 更新时间:2023-11-01 01:28:32 27 4
gpt4 key购买 nike

如果你有一个包含无限数量数组的数组

例如:

var masterArray = [ [1,2,3,4,5],
[1,2],
[1,1,1,1,2,2,2,2,4,4],
[1,2,3,4,5] ];

在 masterArray 中找到最长数组索引的有效方法是什么? (在此示例中索引为 2)。

最佳答案

一行是:

masterArray
.map(a=>a.length)
.indexOf(Math.max(...masterArray.map(a=>a.length)));

但最好缓存 masterArray.map(a=>a.length) 结果。

const lengths = masterArray.map(a=>a.length);
lengths.indexOf(Math.max(...lengths));

请注意,此代码仍会迭代数组至少* 3 次(mapmaxindexOf 分别)。

*展开运算符是为了便于阅读,可以省略


为了提高效率,您应该手动迭代数组。

let max = -Infinity;
let index = -1;
masterArray.forEach(function(a, i){
if (a.length > max) {
max = a.length;
index = i;
}
});

Reduce 方法:

masterArray.reduce((maxI,el,i,arr) => 
(el.length>arr[maxI].length) ? i : maxI, 0);

关于javascript - 查找数组数组中最长数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33577266/

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