Josema Pereira Josema Pereira - 23 days ago 20
Javascript Question

Get the array with highest length from a parent array

What is the best way to get the array with the max length?

I have an array as follows,

main = [[1,2,3],[4],[5,6,7,8][9,0]]


I need to store the array with the max length, in this case

maxArray = main[2]

Answer

Use Array#reduce method.

main = [
  [1, 2, 3],
  [4],
  [5, 6, 7, 8],
  [9, 0]
];

console.log(
  main.reduce(function(a, b) {
    return a.length > b.length ? a : b;
  })
);

Comments