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

后端 未结 8 2094
醉话见心
醉话见心 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:28

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

    For each iteration, the current item's (array) length is compared to the length of the currently longest array found (arrays[acc]) and if greater, the accumulator is set to that index.

    var arrays = [ 
      [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],
      [1,1,1,1,1,1]
    ]
    
    var indexOfLongestArray = arrays.reduce((acc, arr, idx) => {
      console.log(acc, idx, JSON.stringify([arr, arrays[acc]]))
      return arr.length > arrays[acc].length ? idx : acc
    }, 0)
    
    // print result:
    console.log( "longest array is at index: ", indexOfLongestArray )

    Short function:

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

提交回复
热议问题