Quicksort an array of objects

2009-08-05 – 4:14pm

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;
		}
	}
});
2009-08-10 – 12:26 pm

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.

2009-08-10 – 12:57 pm

Yeah, that’d be good. :/ I guess for now all we can do is post them up on blogs, until the MooTools plugin system comes out.

Add your voice

Spam protection by WP Captcha-Free