A-C > Array.sort |
![]() ![]() ![]() |
Array.sort
Availability
Flash Player 5.
Usage
myArray
.sort([
compareFunction]
)
Parameters
compareFunction
An optional comparison function used to determine the sorting order of elements in an array. Given the elements A and B, the orderfunc
parameter can have one of the following three values:
![]() |
-1 if A appears before B in the sorted sequence |
![]() |
0 if A = B |
![]() |
1 if A appears after B in the sorted sequence |
Returns
Nothing.
Description
Method; sorts the array in place, without making a copy. If you omit the compareFunction
parameter, Flash sorts the elements in place using the <
comparison operator.
Example
The following example uses Array.sort
without specifying the compareFunction
parameter:
var fruits = ["oranges", "apples", "strawberries", "pineapples", "cherries"];
trace(fruits.join());
fruits.sort();
trace(fruits.join());
Output:
oranges,apples,strawberries,pineapples,cherries
displays apples,cherries,oranges,pineapples,strawberries
The following example uses Array.sort
with a specified order function.
var passwords = [
"gary:foo",
"mike:bar",
"john:snafu",
"steve:yuck",
"daniel:1234"
];
function order (a, b) {
// Entries to be sorted are in form
// name:password
// Sort using only the name part of the
// entry as a key.
var name1 = a.split(':')[0];
var name2 = b.split(':')[0];
if (name1 < name2) {
return -1;
} else if (name1 > name2) {
return 1;
} else {
return 0;
}
}
for (var i=0; i< password.length; i++) {
trace (passwords.join());
}
passwords.sort(order);
trace ("Sorted:");
for (var i=0; i< password.length; i++) {
trace (passwords.join());
}
Running the previous code displays the following result in the Output window.
daniel:1234
gary:foo
john:snafu
mike:bar
steve:yuck
![]() ![]() ![]() |