views:

271

answers:

2

Hi, I'm trying to sort an array of objects with ActionScript 3.

The array is like this:

var arr:Array = new Array ();
arr.push ({name:"John", date:"20080324", message:"Hi"});
arr.push ({name:"Susan", date:"20090528", message:"hello"});

can I do something with Array.sort(...) method?

+3  A: 

Do what? If you're trying to e.g. sort by name, then date, use Array.sortOn.

arr.sortOn(['name', 'date'])
KennyTM
+2  A: 

Other than using sortOn, which will work for fields like strings and numbers, if you have other objects or more complex logic, you could pass a compare function to the sort() method.

Your compare function will be called by the sort function as many times as neccesary to sort your array. Each time, it will pass to your function two of the arrays' objects. Here, you determine how these two objects sort and tell that to the sort function by returning:

  • a negative number: if the first object comes before the second one
  • a positive number: if the second object comes before the first one
  • 0: if both objects have the same sort order.
Juan Pablo Califano