在 Flex 中使用两个字段对数组集合进行排序

Sort Array Collection Using Two Fields in Flex

我有一个数组集合:

private var arrayCollection:ArrayCollection = new ArrayCollection([
        {Type:L, Name:"DDD"},
        {Type:H, Name:"EEE"},
        {Type:H, Name:"AAA"},
        {Type:L, Name:"AFG"},
        {Type:L, Name:"ZZZ"},
        {Type:H, Name:"XXX"},
        {Type:, Name:"DeSelectAll"},
        {Type:G, Name:"NNN"},
        {Type:L, Name:"CCC"},
        {Type:, Name:"SelectAll"},
        {Type:H, Name:"BBB"},
        {Type:H, Name:"HHH"},
        {Type:L, Name:"LLL"}
    ]);

我想使用这两个字段类型和名称对这个数组集合进行排序。首先,所有记录都将来自类型 "H" 和名称排序,然后所有记录将来自类型 "L" 和名称排序 然后是 "G" 和 "DeSelectAll" 类型列表顶部和 "DeSelectAll" 之后的 "SelectAll"。我想要这样的结果。

Name:"DeSelectAll" Type:""
Name:"SelectAll" Type:""   
Name:AAA Type: H
Name:BBB Type: H
Name:EEE Type: H
Name:HHH Type: H
Name:XXX Type: H
Name:AFG Type: L
Name:CCC Type: L
Name:DDD Type: L
Name:LLL Type: L
Name:ZZZ Type: L
Name:NNN Type: G

请使用 sort() 提供一些代码。

所以基本上你想按类型排序,然后按名称排序,应该像这样工作:

var nameSortField:SortField = new SortField("Name");
var typeSortField:SortField = new SortField("Type");
arrayCollection.sort = new Sort();
arrayCollection.sort.fields = [typeSortField, nameSortField];
arrayCollection.refresh();

编辑:

如果您需要类型 属性 的自定义订单(因此 "G" 位于末尾),您需要类型字段的自定义比较函数:

// This is the sort order for your Type. First empty, then H, then L and then G
// It is not clear if G, H and L are properties in your code. If that are properties you should remove the quotes around G, H and L
private var typeOrder:Array = ["","H", "L", "G"];

var nameSortField:SortField = new SortField("Name");
var typeSortField:SortField = new SortField("Type");
typeSortField.compareFunction = typeCompareFunction;

arrayCollection.sort = new Sort();
arrayCollection.sort.fields = [typeSortField, nameSortField]
arrayCollection.refresh();

private function typeCompareFunction(a:Object, b:Object, fields:Array = null):int
{    
    if (typeOrder.indexOf(a.Type) < typeOrder.indexOf(b.Type))
    {
        // if the a.Type position in the array is before b.Type position the item a should be before b
        return -1;
    }
    else if (typeOrder.indexOf(a.Type) > typeOrder.indexOf(b.Type))
    {
        // if the a.Type position in the array is after b.Type position the item a should be after b
        return 1;
    }
    else
    {
        return 0;
    }
}