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:

var myArray = [[1,2,3],[1,2,3,4],[1,2],[1,2]];

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:

var shortest = myArray.reduce(function(p,c) {return p.length>c.length?c:p;},{length:Infinity});

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