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

后端 未结 8 2113
醉话见心
醉话见心 2021-02-05 09:44

If you have an array containing an indefinite amount of arrays

ex:

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


        
8条回答
  •  猫巷女王i
    2021-02-05 10:32

    One-liner is:

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

    But better to cache masterArray.map(a=>a.length) results.

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

    Note, this code still iterate array at least* 3 times(map, max, indexOf separately).

    *Spread operator is for readability and can be omitted


    For more efficiency you should manual iterate array.

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

    Reduce method:

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

提交回复
热议问题