Skip to content
Advertisement

What’s the best way to find the shortest array in a two dimensional array?

Say for example I have an array that looks like this:

JavaScript

I’m trying to find the first shortest array inside myArray which in this case would be myArray[2].

Obviously I could just write a loop, checking the length of each array and returning the smallest one. What I’m wondering is if there’s a really clean or cleaver way to do it in javascript. Something along the lines of this: http://ejohn.org/blog/fast-javascript-maxmin/

Thanks!

Advertisement

Answer

Well you could do it like this:

JavaScript

This uses an internal loop so it’s faster than manually running your own loop, but would require a shim to work in older browsers.

Advertisement