O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Sorting or Reversing an Array

Problem

You want to sort the elements of an array.

Solution

Use the sort() method. For arrays of objects, you can also use the sortOn() method.

Discussion

You can perform a simple sort on an array using the sort() method. The sort() method, without any parameters, sorts the elements of an array in ascending order. Elements are sorted according to the Unicode code points of the characters in the string (roughly alphabetical for Western European languages).

var words:Array = ["tricycle", "relative", "aardvark", "jargon"];
words.sort();
trace(words); // Displays: aardvark,jargon,relative,tricycle

The sort() method, by default, is very useful if you want to sort the elements of an array in ascending, alphabetical order. However, there are some caveats. Namely, the sort is case-sensitive, and it sorts numbers “alphabetically” instead of numerically. Fortunately, ActionScript allows you to pass one of several constants to the sort() method in order to sort with different guidelines.

You sort an array in descending order using the Array.DESCENDING constant:

var words:Array = ["tricycle", "relative", "aardvark", "jargon"];
words.sort(Array.DESCENDING);
trace(words); // Displays: tricycle,relative,jargon,aardvark

As mentioned, the sort() method runs a case-sensitive sort by default. It places elements starting with uppercase characters before elements starting with lowercase characters. The following illustrates the point:

var words:Array = ["Tricycle", "relative", ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required