Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an Array of MovieClips on values within their child clips

I have a class called Table that is linked to a clip on the stage. During setup I create many Table instances and pass each one an instance of a TableData class. This TableData object includes an ID value.

I put a selection of my Table objects in an Array which I would lik eto sort based on the ID value within each Table's instance of TableData.

What I had hoped to use was something like: myArray.sortOn("tableData.id");

This doesn't seem to work and I assume that Array.sortOn() can't drill down into child clips. Is there a way that I can achieve this?

like image 539
popClingwrap Avatar asked Dec 19 '12 16:12

popClingwrap


1 Answers

The Array and generic Vector.<> collections both provide an alternate form of the .sort() method which takes a function. You can provide your own sorting implementation, in this case which peeks objects and compares only specific pieces of them.

Consider the following class:

class TableData {
    public var ID:String;

    public function TableData(id:String):void {
        this.ID = id;
    }

}

This is a simplified version of your TableData class that only provides a ID. Then a simplified Table class:

class Table {

    private var _data:TableData;

    public function get data():TableData {
        return _data;
    }

    public function Table(tableData:TableData) {
        _data = tableData;
    }

}

Finally, lets put them to use, and spin up a new collection.

var list:Vector.<Table> = new Vector.<Table>();

list.push(new Table(new TableData("X")));
list.push(new Table(new TableData("C")));
list.push(new Table(new TableData("S")));
list.push(new Table(new TableData("A")));

Now, we need to make a new function that will actually do our comparison:

private function sortUsingDataID(a:Table, b:Table):int {
    var aID:String = a.data.ID;
    var bID:String = b.data.ID;
    return aID < bID ? aID == bID ? 0 : -1 : 1;
}

This function will expect to get two items, and should return either -1, 0, or 1. If a should come before b then the function should return -1. Otherwise, if a should come after b, then it should return 1. Lastly, if the two are the same, then it should return a value of 0.

So, now we just need to tell the array to resort itself using our custom sorting function by calling .sort and passing in our function.

list.sort(sortUsingDataID);

Now the list should be sorted the way that you want.

See an working example here.

See the documentation for more details

like image 165
J. Holmes Avatar answered Oct 21 '22 19:10

J. Holmes