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

[sourcecode language=’javascript’]
var objs = [
{fruit:”cherry”},
{fruit:”apple”},
{fruit:”banana”}
];

console.log(objs.sortObjects(‘fruit’));
// Logs [{fruit:”apple”},{fruit:”banana”},{fruit:”cherry”}] to the console
[/sourcecode]

The code

[sourcecode language=’javascript’]
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;
}
}
[/sourcecode]

Implemented on the Array native:

[sourcecode language=’javascript’]
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;
}
}
});
[/sourcecode]

Comments

2 responses to “Quicksort an array of objects”

  1. Oliver Nassar Avatar

    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.

    1. Barry van Oudtshoorn Avatar

      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.

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.

To respond on your own website, enter the URL of your response which should contain a link to this post’s permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post’s URL again. (Find out more about Webmentions.)