Simon Palmer’s blog

January 19, 2009

Sorting flex Arrays by Date

Filed under: code, Flex — simonpalmer @ 2:11 pm

I have been wanting to figure out a reliable way of doing this for a while, and suddenly the necessity arose for me to do it, so I have a solution. As far as I can tell if you have a date field in an object and an array of those objects, then the results of sorting the array are indeterminate.

public class myClass
    public var some_date: Date;

var myArray:Array = new Array();
myArray.push(new myClass);

myArray.sortOn("some_date", Array.NUMERIC);

The above code (so long as the some_date field was populated) never gave me reliable result for the sort order. I googled in vain for a solution and found a couple, but was never really happy with them. I had a flash of inspiration this morning which is really very obvious now I have done it, but is a nice elegant way of handling this situation.

Basically I add a public getter for a new field which just returns the Date objects time value as a Number, e.g.

public class myClass
    public var some_date: Date;
    [Transient] public function get some_date_time():Number
        return some_date.time;

var myArray:Array = new Array();
myArray.push(new myClass);
myArray.sortOn("some_date_time", Array.NUMERIC);

This works a treat and gives me reliable sorting results every time.

In case you are wondering why I use [Transient] it is because I am using RPC and remote objects for the connection back to my server and my classes are generally [Managed]. Without the (undocumented) [Transient] metadata some_date_time would be treated as a legitimate field and an attempt would be made to serialise it back to the server across the RPC boundary. This causes a warning to be thrown in the Flex server framework code which clogs up my logs and feels unprofessional.


1 Comment »

  1. Simon thanks for that, a slick example 🙂

    Cheers, Simon

    Comment by Simon Bailey — March 1, 2009 @ 9:33 pm

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at

%d bloggers like this: