Sorting Javascript Arrays (of Objects)

There’re many ready Javascripts out there, which already allow you to sort arrays. However, if you come from a OO background like me, it won’t be long before you start using Javascript arrays of custome objects. You can’t really use those simple number or string sorting algorithms available, since they don’t inspect the attributes to sort correctly. You could write a custom sort function for that purpose, then rewrite it again and again for each of the attributes of that object, and again and again for all other objects.

Or you could follow that well known Comparable model from Java. By attaching methods to the custom objects [1] like a Comparable, you can write generic sort algorithms to performing sorting. You can even extend the feature to using a Comparator to influence the object’s natural sort order.

Side note: Javascript does not support method overloading, and it doesn’t report and error that it doesn’t [2]. It simply uses the last method declared. I’ve therefore named the other method sortArray2. Bad method name, but you should name it more appropriately if you decide to use it.

Javascript Object Array Sorting Example

[1] Introduction and Features of Javascript “Function” Objects
[2] JavaScript only pretends to support function overloading

Leave a Reply