Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array of objects in ActionScript 3

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?

like image 683
vitto Avatar asked May 23 '10 16:05

vitto


2 Answers

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

arr.sortOn(['name', 'date'])
like image 69
kennytm Avatar answered Sep 28 '22 08:09

kennytm


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.
like image 31
Juan Pablo Califano Avatar answered Sep 28 '22 09:09

Juan Pablo Califano