Quicksort an array of objects

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&#91;i&#93;&#91;key&#93;;
		var currElem = array&#91;i&#93;;
		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&#91;i&#93;&#91;key&#93;;
			var currElem = this&#91;i&#93;;
			var j = i - 1;
			while ((j >= 0) && (this[j][key] > currVal)) {
				this[j + 1] = this[j];
				j--;
			}
			this[j + 1] = currElem;
		}
	}
});

2 thoughts on “Quicksort an array of objects”

  1. Great post. I’ve got a few native type extensions that I’ve written myself and re-use often (really love your ellipsise one).

    Man I wish we had a site where we could contribute these without messing up the moo-core.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.