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

后端 未结 8 2091
醉话见心
醉话见心 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条回答
  • 2021-02-05 10:15

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

    0 讨论(0)
  • 2021-02-05 10:16

    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]
    
    0 讨论(0)
  • 2021-02-05 10:16

    Using lodash:

    _.max(_.map(masterArray, function(v, k) { return { id: k, size: v.length }; }),'size').id;
    

    This creates a new array with objects having 'id' and 'size', then finds the maximum size in that array, and returns its 'id'.

    jsfiddle: https://jsfiddle.net/mckinleymedia/8xo5ywbc/

    0 讨论(0)
  • 2021-02-05 10:19

    Try using while loop

    var masterArray = [
      [1, 2, 3, 4, 5],
      [1, 2],
      [1, 1, 1, 1, 2, 2, 2, 2, 4, 4],
      [1, 2, 3, 4, 5]
    ];
    
    var i = 0, len = masterArray.length;
    
    while (i < len) {
      // if array[i + 1] exists
      // and array[i + 1] length greater than array[i] length
      // and i + 1 equals array length - 1
      // break
      if (masterArray[i + 1] 
          && masterArray[i + 1].length < masterArray[i].length 
          && i + 1 === len - 1) {
        break
      } 
      // else increment i
      else {
        ++i
      }
    }
    
    console.log(masterArray[i])

    0 讨论(0)
  • 2021-02-05 10:23

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

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

    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));

    0 讨论(0)
  • 2021-02-05 10:24

    .reduce is the nicest way to do this:

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

    Or with ES6:

    masterArray.reduce((p, c, i, a) => a[p].length > c.length ? p : i, 0);
    
    0 讨论(0)
提交回复
热议问题