Suppose I have a Javascript array, like so:
var test = [\'b\', \'c\', \'d\', \'a\'];
I want to sort the array. Obviously, I can just do th
Array.prototype.sortIndices = function (func) {
var i = j = this.length,
that = this;
while (i--) {
this[i] = { k: i, v: this[i] };
}
this.sort(function (a, b) {
return func ? func.call(that, a.v, b.v) :
a.v < b.v ? -1 : a.v > b.v ? 1 : 0;
});
while (j--) {
this[j] = this[j].k;
}
}
YMMV on how you feel about adding functions to the Array prototype and mutating arrays inline, but this allows sorting of an array of any objects that can be compared. It takes an optional function that can be used for sorting, much like Array.prototype.sort
.
An example,
var test = [{b:2},{b:3},{b:4},{b:1}];
test.sortIndices(function(a,b) { return a.b - b.b; });
console.log(test); // returns [3,0,1,2]