如果你有一个包含无限数量数组的数组
例如:
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 次(map
、max
、indexOf
分别)。
*展开运算符是为了便于阅读,可以省略
为了提高效率,您应该手动迭代数组。
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/