Find the index of the longest array in an array of arrays
masterArray.reduce(function(a,i,ii){
if (ii === 1){
return a
};
if (i.length > a.length){
return i
}
return a
})
One-liner is:
masterArray
.map(a=>a.length)
.indexOf(Math.max(...masterArray.map(a=>a.length)));
But better to cache masterArray.map(a=>a.length)
results.
const lengths = masterArray.map(a=>a.length);
lengths.indexOf(Math.max(...lengths));
Note, this code still iterate array at least* 3 times(map
, max
, indexOf
separately).
*Spread operator is for readability and can be omitted
For more efficiency you should manual iterate array.
let max = -Infinity;
let index = -1;
masterArray.forEach(function(a, i){
if (a.length > max) {
max = a.length;
index = i;
}
});
Reduce
method:
masterArray.reduce((maxI,el,i,arr) =>
(el.length>arr[maxI].length) ? i : maxI, 0);
.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);
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)