Sorting Values Stored in a Dictionary

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;
		}
	}
}
This entry was posted in ActionScript 3 and tagged , , . Bookmark the permalink.

4 Responses to Sorting Values Stored in a Dictionary

  1. Vish says:

    Thank you for telling this.

  2. Martin Copp says:

    Exactly what I needed, thanks!

  3. Sean says:

    Thanks sir! Saved me a good chunk of time and effort with this. Good clean stuff.
    – Sean

  4. Bob says:

    THANKS A LOT, WORKS FINE !

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">