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

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

提交回复
热议问题