RNJ
RNJ

Reputation: 15572

Flex sort array collection by inner class

I want to sort an array collection in a way that I am not sure is possible.

Usually when you want to sort you have something like this.

var dataSortField1:SortField = new SortField();
dataSortField1.name = fieldOneToSortBy;
dataSortField1.numeric = fieldOneIsNumeric;

var dataSort:Sort = new Sort();
dataSort.fields = [dataSortField1];

arrayCollection.sort = dataSort;
arrayCollection.refresh();

so if I had a class

public class ToSort {
    public var int:a
}

I could type

var ts1:ToSort = new ToSort();  
ts1.a = 10;
var ts2:ToSort = new ToSort();  
ts2.a = 20;
var arrayCollection:ArrayCollection = new ArrayCollection([ts1, ts2])
var dataSortField1:SortField = new SortField();
dataSortField1.name = "a";
dataSortField1.numeric = true;

var dataSort:Sort = new Sort();
dataSort.fields = [dataSortField1];

arrayCollection.sort = dataSort;
arrayCollection.refresh();

This works fine. My problem is I now have inherited a class that has another class inside it and I need to sort against this as well. For example

public class ToSort2 {
    public var int:a
    public var ToSortInner: inner1
}

public class ToSortInner {
    public var int:aa
    public var int:bb
}

if a is the same in multiple classes then I want to sort on ToSortInner2.aa Is this possible. I have tried to pass in inner1.aa as the sort field name but this does not work.

Hope this is clear. If not I'll post some more code.

Thanks

Upvotes: 0

Views: 685

Answers (2)

JeffryHouser
JeffryHouser

Reputation: 39408

You need to write a custom sort compareFunction. You can drill down into the objects properties inside the function.

Conceptually something like this:

public function aSort(a:Object, b:Object, fields:Array = null):int{
  if(a.aa is b.aa){
    return 0
  } else if(a.aa > b.aa) {
    return 1
  } else{
    return -1
  }
}

When you create your sort object, you can specify the compare function:

var dataSort:Sort = new Sort();
dataSort.compareFunction = aSort;

arrayCollection.sort = dataSort;
arrayCollection.refresh();

Upvotes: 2

Amy Blankenship
Amy Blankenship

Reputation: 6961

Sort also has another property, compareFunction.

Upvotes: 0

Related Questions