User Guide

232 Working with Arrays
You may find that you need to sort your array without regard to case, or in descending order,
or perhaps your array contains numbers that you want to sort numerically instead of
alphabetically. The
sort() method has an options parameter that allows you to alter each
characteristic of the default sort order. The options are defined by a set of static constants in
the Array class, as shown in the following list:
Array.CASEINSENSITIVE: This option makes the sort disregard case. For example, the
lowercase letter b precedes the uppercase letter D.
Array.DESCENDING: This reverses the default ascending sort. For example, the letter B
precedes the letter A.
Array.UNIQUESORT: This causes the sort to abort if two identical values are found.
Array.NUMERIC: This causes numerical sorting, so that 3 precedes 10.
The following example highlights some of these options. An array named
poets is created
that is sorted using several different options.
var poets:Array = ["Blake", "cummings", "Angelou", "Dante"];
poets.sort(); // default sort
trace(poets); // output: Angelou,Blake,Dante,cummings
poets.sort(Array.CASEINSENSITIVE);
trace(poets); // output: Angelou,Blake,cummings,Dante
poets.sort(Array.DESCENDING);
trace(poets); // output: cummings,Dante,Blake,Angelou
poets.sort(Array.DESCENDING | Array.CASEINSENSITIVE); // use two options
trace(poets); // output: Dante,cummings,Blake,Angelou
You can also write your own custom sort function, which you can pass as a parameter to the
sort() method. For example, if you have a list of names in which each list element contains a
persons full name, but you want to sort the list by last name, you must use a custom sort
function to parse each element and use the last name in the sort function. The following code
shows how this can be done with a custom function that is used as a parameter to the
Array.sort() method:
var names:Array = new Array("John Q. Smith", "Jane Doe", "Mike Jones");
function orderLastName(a, b):int
{
var lastName:RegExp = /\b\S+$/;
var name1 = a.match(lastName);
var name2 = b.match(lastName);
if (name1 < name2)
{
return -1;
}
else if (name1 > name2)