User Guide

Indexed arrays 233
{
return 1;
}
else
{
return 0;
}
}
trace(names); // output: John Q. Smith,Jane Doe,Mike Jones
names.sort(orderLastName);
trace(names); // output: Jane Doe,Mike Jones,John Q. Smith
The custom sort function orderLastName() uses a regular expression to extract the last name
from each element to use for the comparison operation. The function identifier
orderLastName is used as the sole parameter when calling the sort() method on the names
array. The sort function accepts two parameters,
a and b, because it works on two array
elements at a time. The sort functions return value indicates how the elements should be
sorted:
A return value of -1 indicates that the first parameter, a, precedes the second parameter, b.
A return value of 1 indicates that the second parameter, b, precedes the first, a.
A return value of 0 indicates that the elements have equal sorting precedence.
The
sortOn() method is designed for indexed arrays with elements that contain objects.
These objects are expected to have at least one common property that can be used as the sort
key. The use of the
sortOn() method for arrays of any other type yields unexpected results.
The following example revises the
poets array so that each element is an object instead of a
string. Each object holds both the poets last name and year of birth.
var poets:Array = new Array();
poets.push({name:"Angelou", born:"1928"});
poets.push({name:"Blake", born:"1757"});
poets.push({name:"cummings", born:"1894"});
poets.push({name:"Dante", born:"1265"});
poets.push({name:"Wang", born:"701"});
You can use the sortOn() method to sort the array by the born property. The sortOn()
method defines two parameters,
fieldName and options. The fieldName argument must be
specified as a string. In the following example,
sortOn() is called with two arguments,
"
born" and Array.NUMERIC. The Array.NUMERIC argument is used to ensure that the sort is
done numerically instead of alphabetically. This is a good practice even when all the numbers
have the same number of digits because it ensures that the sort will continue to behave as
expected if a number with fewer or more digits is later added to the array.
poets.sortOn("born", Array.NUMERIC);
for (var i:int = 0; i < poets.length; ++i)