在数组数组中找到最长数组的索引 [英] Find the index of the longest array in an array of arrays
本文介绍了在数组数组中找到最长数组的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果您的数组包含不确定数量的数组
If you have an array containing an indefinite amount of arrays
例如:
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).
What is an efficient way to find the index of the longest array in masterArray? (in this example index would be 2).
推荐答案
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.map(function(a){return a.length;}).indexOf(Math.max.apply(Math, masterArray.map(function(a){return a.length;})));
但是更好地缓存map
结果.
var lengths = masterArray.map(function(a){return a.length;});
lengths.indexOf(Math.max.apply(Math, lengths));
注意,即使这段代码也对数组进行3次迭代(分别为map
,max
,indexOf
).
为了提高效率,您应该手动迭代数组.
Note, even this code iterate array 3 times(map
, max
, indexOf
separately).
For more efficient you should manual iterate array.
var max = -Infinity;
var index = -1;
masterArray.forEach(function(a, i){
if (a.length>max) {
max = a.length;
index = i;
}
});
Reduce
方法:
Reduce
method:
masterArray.reduce(function(maxI,el,i,arr) {return el.length>arr[maxI].length ? i : maxI;}, 0)
这篇关于在数组数组中找到最长数组的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文