Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an ArrayCollection in Flex

Tags:

apache-flex

Is there any way in Flex where in we can sort an arraycollection based on strings .

I have a dataprovider with strings like "Critical" "High" "Medium" "Low" where in I need to sort it in such a way that I need Critical to be displayed on the top and next High , Medium and Low follows.

Can somebody let me know any logic .

Thanks, Kumar

like image 937
skumarvarma Avatar asked Oct 21 '09 17:10

skumarvarma


1 Answers

ArrayCollection is a subclass of ListCollectionView that has a sort property. The Sort class has a compareFunction property that you can use to define custom sort functions.

private function sortFunction(a:Object, b:Object, array:Array = null):int
{
   //assuming that 'level' is the name of the variable in each object 
   //that holds values like "Critical", "High" etc
   var levels:Array = ["Low", "Medium", "High", "Critical"];
   var aLevel:Number = levels.indexOf(a.level);
   var bLevel:Number = levels.indexOf(b.level);
   if(aLevel == -1 || bLevel == -1)
      throw new Error("Invalid value for criticality ");
   if(aLevel == bLevel)
      return 0;
   if(aLevel > bLevel)
      return 1;
   return -1;
}
var sort:Sort = new Sort();
sort.compareFunction = sortFunction;
arrayCollection.sort = sort;
arrayCollection.refresh();
like image 146
Amarghosh Avatar answered Nov 06 '22 22:11

Amarghosh