Sorting things

July 29, 2006   [Modified August 2 -- improved strSort]

So you have this nice array of objects -- much like a database table -- in JavaScript, but JavaScript's built in array method sort() only works on arrays of strings. How do you sort your objects? Let's sort it out...

Works equally well in JavaScript & ActionScript

First you will need to download objSort.js (2 kB). This small script works equally well in JavaScript and ActionScript 1. Include it in your code like this:
<script type="text/javascript" src="objSort.js"></script>
#include "objSort.js"

How to use -- similar to "order by" in SQL

The script extends the Array prototype -- all arrays get a new method called objSort. Here's how to use it:
var a=[

/*   Now a will be sorted like this:

As you can see this works much like order by in SQL -- it takes an unlimited number of arguments, each is the name of an object member/"column".
To sort something in a descending order add -1 after the argument:
/*   Now a will be sorted like this:

Which data types can you sort?

Currently you can sort the following data types:

Please note:

An extra bonus -- customizable string sorting

Actually there is one more array method that objSort.js adds -- strSort(). By default it acts just like the built in sort() -- but you can customize it to work differently:
if(!alert && trace){alert=trace}; // alert-->trace if run in ActionScript

var a=["ape","Banana","cucumber","* asterix"];

 // This will return * asterix, Banana,ape,cucumber 
// (capitals first, asterix before characters)

 // This will return * asterix,ape,Banana,cucumber 
// (asterix before characters, but we ignore case)

 // This will return ape,Banana,cucumber,* asterix
// (we sort with "*" in a new alphanumeric place, after "z")

As you can see we can control the sort order using two different flags, both assignable as object members to our array.
The first flag sortIgnoreCase can only be true or false (boolean). If it is true we ignore the character case -- i.e. things get sorted as if every string had undergone a toLowerCase() transformation.
The second flag sortCharOrder is a more complex beast -- it is an array (or comma separated string) where each element is a string which consists of:
  1. The character (x) we want to give a new place in our alphabet.
  2. The character (y) we want to place x before or after.
  3. An underscore sign if we want to place x after y.

You can add your favourite values for these flags directly to the Array.prototype -- they will then apply to all arrays where you don't specifically set them different:
// Now all arrays where we don't specifiy anything else
// get sorted with ignoreCase on


That's really all there is to it -- now you should be able to sort your own things out. To make it easier to study the results of your object sorting I recommend that you use a JSON stringifier.