Sorting Values Stored in a Dictionary

15th June, 2009 – 7:59 am

Looking through my incoming seaches from Google I’ve noticed that a lot of visitors to my site are trying to figure out how to sort values stored in a Dictionary. The short and simple answer is that you can’t as Dictionary’s in AS3 are meant to represent un-ordered HashMaps, however, there’s nothing to stop you moving the un-ordered data out of the Dictionary and into an Array:

package {
        import flash.display.Sprite;
        import flash.utils.Dictionary;

        /**
         * @author Jonny Reeves
         */

        public class DictionarySort extends Sprite
        {
                function DictionarySort() : void
                {
                        var myDictionary : Dictionary = new Dictionary();
                       
                        // Provide some values to sort.
                        myDictionary[500] = "Five Hundred";
                        myDictionary[55] = "Fifty Five";
                        myDictionary[1] = "One";
                        myDictionary[231] = "Two Hundred and Thirty One";
                       
                        var myKeys : Array = this.extractKeysFrom(myDictionary);
                        trace("myKeys Array before sort: " + myKeys);
                       
                        // Apply a Numeric sort to the Array.
                        myKeys.sort(Array.NUMERIC);
                        trace("myKeys Array after sort: " + myKeys);
                       
                        // You can now use the extracted Keys to read from the Dictionary in
                        // the required order.
                        for each (var thisKey : * in myKeys)
                        {
                                // Will trace out the number followed by the english words.
                                trace(thisKey + " = " + myDictionary[thisKey]);
                        }
                }
               
                /**
                 * Helper method to extract the Keys from a Dictionary Object and return
                 * them in an Array.
                 */

                private function extractKeysFrom(source : Dictionary) : Array
                {
                        var output : Array = [];
                       
                        // Note that Dictionary’s Keys are untyped as they can contain
                        // any value.
                        for (var prop : * in source)
                        {
                                output.push(prop);
                        }
                        return output;
                }
        }
}
 

Post a Comment