How to find the index of the longest array in an array of arrays with JavaScript?

Sometimes, we want to find the index of the longest array in an array of arrays with JavaScript.

In this article, we’ll look at how to find the index of the longest array in an array of arrays with JavaScript.

How to find the index of the longest array in an array of arrays with JavaScript?

To find the index of the longest array in an array of arrays with JavaScript, we can use some array methods and Math.max.

For instance, we write:

const arr = [
  [1, 2, 3, 4, 5],
  [1, 2],
  [1, 1, 1, 1, 2, 2, 2, 2, 4, 4],
  [1, 2, 3, 4, 5]
];
const lengths = arr
  .map(a => a.length)
const index = lengths
  .indexOf(Math.max(...lengths));
console.log(index)

to get the lengths of each array in arr with:

const lengths = arr
  .map(a => a.length)

Then we call lengths.indexOf to return the index of the array with the longest length.

We get the longest length with Math.max(...lengths).

We spread the lengths entries as arguments for Math.max to find the longest length.

Therefore, index is 2 since the 3rd array is the longest.

Conclusion

To find the index of the longest array in an array of arrays with JavaScript, we can use some array methods and Math.max.