Sorting in AS2

One of the things you can’t get away from in data visualization is sorting. It’s important for drawing the visualizations. It’s also important for user expectations. All users are used to an OS where you can sort. They will expect the same for a visualization. Sorting in AS1 was slow. I ended up writing includes for all my sorting. AS2 compiles down to AS1 byte code, so most performance is identical (although Player 7 is a lot faster than 6). But, the one area with really significant speed increase was the sorting.

For code I use all the time, I usually end up writing a wrapper around the base class or method. When I wrote this sorting wrapper, I found one thing that was really useful - using options 17 and 19 will sort numbers, strings, and booleans. (Dates are the exception and you need to convert them to millisecond values (getTime()) to sort them as numbers.) So, you could secondary sort using properties of different type.

What am I talking about? First, a few definitions…

sortOn - sorting an array of objects by a property - E.g., a person could have many properties - age, name, etc. To sort by name, you would use: people.sortOn(”name”)

Secondary sorting - sorting by more than one property. E.g., sorting all baseball players by team, then name, would result in a list of players grouped by team. And, within each team, they would be sorted alphabetically.

Sort option - how you want to sort alphabetical, numeric, reverse numeric, etc.

In Player 7 you can secondary sort, but, all sorting needs to use the same option (Player 8 supports multiple options). However, since options 17 and 19 will correctly sort both numbers and strings (17 and 19 are case insensitive string sorts - change to 16 and 18 for case sensitive), you can correctly sort e.g., name then age. (Always use numbers for option codes btw - NUMERIC is slower than 16).

My tests showed that using option 17 or 19 is just as fast as other sorts. The one exception is passing no option, which is the fastest, but, will only sort as case-insensitive string.

One more thing - I always use sortOn and not sort. I believe sort is slower (or at least it used to be). But more importantly, it always seems to make more sense to have your data structured as arrays of objects, as you almost always need to have more than one property for a piece of data.

Here’s how to use…

var rec_array:Array = new Array();
rec_array.push({name:"john", city:"omaha", zip:68144});
rec_array.push({name:"john", city:"kansas city", zip:72345});
rec_array.push({name:"bob", city:"omaha", zip:94010});
rec_array.push({name:"bob", city:"omaha", zip:9});
ArrayMethods.smartSortOn(rec_array, ['name', 'city','zip']);

And here’s the code and sample.

Comments

One Response to “Sorting in AS2”

  1. Michael Ypes on September 26th, 2007 3:02 am

    Nice bit of code, exactly what I was looking for and saved me a few hours. Thanks :)

Leave a Reply