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

后端 未结 8 2095
醉话见心
醉话见心 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: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));

提交回复
热议问题