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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33577266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:38:50  来源:igfitidea点击:

Find the index of the longest array in an array of arrays

javascriptarrays

提问by jmancherje

If you have an array containing an indefinite amount of arrays

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

ex:

前任:

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

What is an efficient way to find the index of the longest array in masterArray? (in this example index would be 2).

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

采纳答案by vp_arth

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

One-liner is:

单线是:

masterArray.map(function(a){return a.length;}).indexOf(Math.max.apply(Math, masterArray.map(function(a){return a.length;})));

But better to cache mapresults.

但最好缓存map结果。

var lengths = masterArray.map(function(a){return a.length;});
lengths.indexOf(Math.max.apply(Math, lengths));

Note, even this code iterate array 3 times(map, max, indexOfseparately).
For more efficient you should manual iterate array.

请注意,即使此代码迭代数组 3 次(map, max,indexOf分别)。
为了更高效,您应该手动迭代数组。

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


Reducemethod:

Reduce方法:

masterArray.reduce(function(maxI,el,i,arr) {return el.length>arr[maxI].length ? i : maxI;}, 0)

回答by Downgoat

.reduceis the nicest way to do this:

.reduce是最好的方法:

masterArray.reduce(function (pending, cur, index, ar) { ar[ pending ].length > cur.length ? pending : index }, 0);

Or with ES6:

或者使用 ES6:

masterArray.reduce((p, c, i, a) => a[p].length > c.length ? p : i, 0);

回答by Guilherme Souza

masterArray.reduce(function(a,i,ii){
  if (ii === 1){
    return a
  };
  if (i.length > a.length){
    return i
  }
  return a
})

回答by vsync

A reducer iterates the array of arrays, where the accumulator represents the index of the longest array, starting with index 0.

reducer 迭代数组数组,其中累加器表示最长数组的索引,从 index 开始0

For each iteration, the current item's (which is an array) length is compared to the length of the array by index (accumulator) from the list of arrays, and if greater, the accumulator is incremented.

对于每次迭代,当前项(它是一个数组)的长度与数组列表中的索引(累加器)的数组长度进行比较,如果更大,则累加器递增。

var arrays = [ 
  [1,1,1,1,1],
  [1,1], 
  [1,1,1,1,1,1,1,1,1,1],   // ? The longest, which is at index 2
  [1,1,1,1] 
]

var indexOfLongestArray = arrays.reduce((idx, arr) => 
  arr.length > arrays[idx].length ? idx + 1 : idx
, 0)


// print result:
console.log( indexOfLongestArray )

回答by djvs

Lazy UnderscoreJS approach:

懒惰的 UnderscoreJS 方法:

_.max(masterArray, function(i){ return i.length; })

回答by djvs

Sort a list of indexes by length in descending order, and take the first one:

按长度降序对索引列表进行排序,并取第一个:

a.map((e, i) => i) . sort((i, j) => a[j].length - a[i].length) [0]

回答by P?r Eriksson

If you are using Lodash (since version 4.0)you can easily use _.maxByand _.sizeas iteratee:

如果您使用的是 Lodash (从 4.0 版开始),您可以轻松地使用_.maxBy_.size作为 iteratee:

_.maxBy(masterArray, _.size) -> [1, 1, 1, 1, 2, 2, 2, 2, 4, 4]

To find the minimum use _.minBy

找到最低限度的使用 _.minBy

_.minBy(masterArray, _.size) -> [1, 2]

回答by rowad

I faced this today, and found this question.

我今天遇到了这个,并发现了这个问题。

Here is a more modern approach:

这是一种更现代的方法:

const longestArray = masterArray.reduce((acc, curr, index) =>
    curr.length > acc.length ? index : index - 1
);
  • the code now finds the index of the longest array not the longest array it self (sorry misread the question).
  • 代码现在找到最长数组的索引而不是它自己的最长数组(抱歉误读了问题)。

回答by shuts13

if order of elments in array for you does not matter, and you want just use the Longest array, you can sort array by length

如果数组中元素的顺序对您来说无关紧要,而您只想使用最长的数组,则可以按长度对数组进行排序

      masterArray.sort((a, b) => b.length - a.length);
      const theLongest = masterArray[0];

in this case first element will be always the Longest

在这种情况下,第一个元素将始终是最长的

回答by just95

You can iterate over all entries of the outer array using a forloop and compare the length of each of its items to the longest array you have found so far.

您可以使用循环遍历外部数组的所有条目,for并将其每个项目的长度与您迄今为止找到的最长数组进行比较。

The following function returns the index of the longest array or -1if the array is empty.

以下函数返回最长数组的索引或-1数组是否为空。

function indexOfLongest(arrays) {
  var longest = -1;
  for (var i = 0; i < arrays.length; i++) {
    if (longest == -1 || arrays[i].length > arrays[longest].length) {
      longest = i;
    }
  }
  return longest;
}  

var masterArray = [ [1,2,3,4,5],
                    [1,2], 
                    [1,1,1,1,2,2,2,2,4,4],
                    [1,2,3,4,5] ];
document.write(indexOfLongest(masterArray));