A-C > Array.sort
Array.sortSyntax
myArray
.sort();
myArray
.sort(
orderfunc
);
Arguments
orderfunc
An optional comparison function used to determine the sorting order. Given the arguments A and B, the specified ordering function should perform a sort as follows:
![]() |
-1 if A appears before B in the sorted sequence |
![]() |
0 if A = B |
![]() |
1 if A appears after B in the sorted sequence |
Description
Method; sorts the array in place, without making a copy. If you omit the orderfunc
argument, Flash sorts the elements in place using the <
comparison operator.
Player
Flash 5 or later.
Example
The following example uses Array.sort
without specifying the orderfunc
argument:
var fruits = ["oranges", "apples", "strawberries",
"pineapples", "cherries"];
trace(fruits.join());
fruits.sort();
trace(fruits.join());
Output:
oranges,apples,strawberries,pineapples,cherries
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());
}
Output:
daniel:1234
gary:foo
john:snafu
mike:bar
steve:yuck