Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the array with highest length from a parent array

Tags:

javascript

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]
like image 650
Josema Pereira Avatar asked Jul 25 '26 04:07

Josema Pereira


1 Answers

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;
  })
);
like image 55
Pranav C Balan Avatar answered Jul 26 '26 20:07

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!