Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flex Dictionary Sorting

I have the following dictionary in flex, and i d like to sort it by value. Couldn't find any resource.

'1'=>2, '0' =>1, '3'=>4 ..

Any ideas ? How can i sort this by value ?

like image 231
DarthVader Avatar asked Dec 06 '22 04:12

DarthVader


2 Answers

I searched around for a similar solution, except that I needed to sort the dictionary map and return a sorted collection relating key value pairs. After failing to find a published solution I put together the approach below. This method takes a dictionary as input, creates an array maintaining the association then sorts the resultant array using array.sortOn() and returns the sorted results back as an array. "key" and "value" fields in the array in the example below are used for clarity, but any field name could be used.

This example assumes a string object as a key and a numeric object as a value, though of course any object type could be used, and field parameters adjusted.

The approach below could also be used for sorting by key instead of value by using "key" as the sort field for the sortOn method, and you could use different sort options than the descending numeric sort I used here( AS3 SortOn() documentation) Code below is intentionally non-generic to simplify it for example purposes.

      public static function sortDictionaryByValue(d:Dictionary):Array
        {
          var a:Array = new Array();
          for (var dictionaryKey:Object in d)
          {
            a.push({key:dictionaryKey,value:d[dictionaryKey]});
          }
          a.sortOn("value",[Array.NUMERIC|Array.DESCENDING]);
          return a;
        }   
like image 57
DavidRFoote Avatar answered Jan 11 '23 11:01

DavidRFoote


Probably not the best way to do it but it works:

var a:Array = new Array();
for each (var v:Number in dict)
{
  a.push(v);
}

a.sort();
like image 25
James Ward Avatar answered Jan 11 '23 13:01

James Ward