Sort an array of Objects by Date
October 20th, 2006 . by polyGeekSort an array of Objects by Date.
The sortOn method doesn’t sort by Date objects. If you need to sort by the date object then try this.
Suppose you have an associative array- myArray - with one of the properties being an instance of Date.
What you can do is add another property to each object that is the date converted to a number.
for(var i:Number = 0; i < myArray.length; ++i) {
}
Now you have a number that you can sort by using sortOn as such:
a.sortOn(”dateNum”);
All sorted now.
Here’s a coded example (download FLA)
var myArray:Array = new Array();
myArray.push({fName: “Dan”, age: “oldest”});
myArray[0].born = new Date(1980, 0, 1);
/*
We want ‘born’ to be an instance of the Date object. We cannot
achieve that in the Array constructor. If we try ‘born’ will
be a typeof String. To work around that we just add it on afterwards.
*/
myArray.push({fName: “Bob”, age: “middle”});
myArray[1].born = new Date(1990, 0, 1);
myArray.push({fName: “Ann”, age: “youngest”});
myArray[2].born = new Date(2000, 0, 1);
myArray.push({fName: “Tim”, age: “middle”});
myArray[3].born = new Date(1990, 0, 1);
for(var i:Number = 0; i < myArray.length; ++i) {
var dateNum:Number = myArray[i].born.getTime();
myArray[i].dateNum = dateNum;
trace(”Before sort: ” + myArray[i].fName + ” : ” + myArray[i].age + ” : ” + myArray[i].born);
}
trace(newline);
myArray.sortOn(”dateNum”, Array.DESCENDING);
for(var i:Number = 0; i < myArray.length; ++i) {
trace(”After sort: ” + myArray[i].fName + ” : ” + myArray[i].age + ” : ” + myArray[i].born);
}











