Ryan Epp
Ryan Epp

Reputation: 951

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!

Upvotes: 2

Views: 5990

Answers (4)

Yilmaz
Yilmaz

Reputation: 49182

Using javascript array reduce. Remember that a reducer will only return one value, we will be reducing the array into a value.

   reduce(callback,initialValue)

JavaScript invokes the callback function upon each item of the array

const findShortestArray = (arr = []) => {
  //  we iterate over array and "val" is the current array element that we are on
  // acc is the current result so far
  const res = arr.reduce((acc, val, index) => {
    if (!index || val.length < acc[0].length) {
      return [val];
    }
    if (val.length === acc[0].length) {
      acc.push(val);
    }
    return acc;
  // initial value=[]
  }, []);
  return res;
};

Upvotes: 0

Joel
Joel

Reputation: 4762

If by best you mean fastest time.. You will not achive a solution that is better than O(N), since you must check each element in the array (assuming it is unsorted).

Since you cannot achieve anything better than O(N), I see no reason not to do something like the following:

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

var shortestIndex = 0;

for( var i=1; i< myArray.length; i++){
    if(myArray[shortestIndex].length > myArray[i].length)
        shortestIndex = i;
}

now myArray[shortestIndex] is the shortest array.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

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.

Upvotes: 9

Zack Argyle
Zack Argyle

Reputation: 8407

The way you are looking for using max or min looks like this.

Math.max.apply(Math, $.map(array, function (index) { return index.length }));

The trick is mapping to the inner arrays length attribute.

Upvotes: 1

Related Questions