Often, you will need to sort an array of objects in Javascript. The inbuilt sort() function can’t do this, but here is a Quicksort implementation for doing just this.
Parameters
array The array to be sorted. (See below for an implementation on the Array Native itself, which makes this variable unnecessary).
key The key to sort by. Make sure every object in your array has this key.
Examples
var objs = [
{fruit:"cherry"},
{fruit:"apple"},
{fruit:"banana"}
];
console.log(objs.sortObjects('fruit'));
// Logs [{fruit:"apple"},{fruit:"banana"},{fruit:"cherry"}] to the console
The code
sortObjects: function(array, key) {
for (var i = 0; i < array.length; i++) {
var currVal = array[i][key];
var currElem = array[i];
var j = i - 1;
while ((j >= 0) && (array[j][key] > currVal)) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = currElem;
}
}
Implemented on the Array native:
Array.implement({
sortObjects: function(key) {
for (var i = 0; i < this.length; i++) {
var currVal = this[i][key];
var currElem = this[i];
var j = i - 1;
while ((j >= 0) && (this[j][key] > currVal)) {
this[j + 1] = this[j];
j--;
}
this[j + 1] = currElem;
}
}
});