0

I have an Array which has Class instances in it. These class instances have several properties. Let's say I want to sort this array by the name property of each instance.

public class Thing
{

    public var name:String;

    public function Thing(name:String)
    {
         this.name = name;
    }
}

And here is what the Array might look like:

var ar:Array = new Array(new Thing("Apple"), new Thing("Compass"), 
                         new Thing("Banana"), new Thing("Alligator"));

After sorting it and looping through it to trace each instance's name property, it should output like this: Alligator, Apple, Banana, Compass

2 Answers2

0

You could sort by

ar.sortOn(property, options);

in your case the property would be "name" and option would ARRAY.ASCENDING

PS: I havent tried, but give it a go: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#sortOn()

sabkaraja
  • 342
  • 4
  • 15
0

sortOn should probably work, or you can pass it through your own custom sort function:

private function _sortArray( a:Thing, b:Thing ):int
{
    if ( a.name < b.name )
        return -1; // a goes before b
    else if ( a.name > b.name )
        return 1; // b goes before a
    return 0; // order doesn't matter
}

You can then call it via:

ar.sort( _sortArray );

Sort functions take two parameters of the type stored in the array (in your case, Thing), and return either <= -1 if a should go before b, >= 1 if b should go before a, or 0 if the order doesn't matter (i.e. the names are the same). You can compare pretty much anything to get the sorting you want. E.g., to get a random sort:

private function _sortArray( a:Thing, b:Thing ):int
{
    if ( Math.random() < 0.5 )
        return -1;
    return 1;
}