'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!
Solution 1:[1]
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.
Solution 2:[2]
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.
Solution 3:[3]
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.
Solution 4:[4]
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;
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Zack Argyle |
| Solution 3 | |
| Solution 4 |
