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

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

提交回复
热议问题