sort outer array based on values in inner array, javascript
Array#sort
(see section 15.4.4.11 of the spec, or MDC) accepts an optional function parameter which will be used to compare two entries for sorting purposes. The function should return -1 if the first argument is "less than" the second, 0 if they're equal, or 1 if the first is "greater than" the second. So:
outerArray.sort(function(a, b) {
var valueA, valueB;
valueA = a[1]; // Where 1 is your index, from your example
valueB = b[1];
if (valueA < valueB) {
return -1;
}
else if (valueA > valueB) {
return 1;
}
return 0;
});
(You can obviously compress that code a bit; I've kept it verbose for clarity.)
Here is a solution not needing a separate variable to contain the index
var arr = [.....]
arr.sort((function(index){
return function(a, b){
return (a[index] === b[index] ? 0 : (a[index] < b[index] ? -1 : 1));
};
})(2)); // 2 is the index
This sorts on index 2
Here used to be a sort implementation that returned the result of a simple x<y
comparison. This solution is disencouraged and this post is left only to preserve the ensuing discussion.