我有一个数组集合:
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"}
]);
我想使用这两个字段Type和Name对此数组集合进行排序。首先,所有记录都将带有名称排序的类型“H”,之后所有记录将来自名称排序的类型“L”并且在列表顶部的“G”和“DeSelectAll”类型之后和“SelectAll”在“DeSelectAll”之后。我想要这样的结果。
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()提供一些代码。
答案 0 :(得分:3)
所以基本上你想要对Type进行排序,然后对Name进行排序,应该使用类似的东西:
var nameSortField:SortField = new SortField("Name");
var typeSortField:SortField = new SortField("Type");
arrayCollection.sort = new Sort();
arrayCollection.sort.fields = [typeSortField, nameSortField];
arrayCollection.refresh();
编辑:
如果您需要Type属性的自定义订单(因此" G"最后),您需要为Type字段设置自定义比较功能:
// 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;
}
}