// This works as expected...
var animals = ["zebra", "ape"];
animals.sort( );
trace(animals); // Displays: "ape,zebra"
// Cool! What a handy little method.
// Watch out, the sort order is not strictly alphabetical...The
// capital "Z" in zebra comes before the lowercase "a" in "ape".
var animals = ["Zebra", "ape"];
animals.sort( );
trace(animals); // Displays: "Zebra,ape". Oops. See Appendix B.
arrayName.sort(compareFunction)
where compareFunction is the name of the
function that tells the interpreter how to make its sorting
decisions.
To build a compare function, we start with a new function that
accepts two arguments (these represent any two elements in the
array). In the function's body, we determine, however we see
fit, which of the elements we'd like to appear earlier in the
element list after a sort( ). If we want the
first element to appear before the second
element, we return a negative number from our
function. If we want the first element to appear
after the second element, we return a
positive number from our function. If we want
the elements to be left in the same positions, we return
from our function. In pseudocode, the approach generically looks like
this:
function compareElements (element1, element2) {
if (element1 should appear before element2) {
return -1;
} else if (element1 should appear after element2) {
return 1;
} else {
return 0; // The elements should be left alone
}
}
For example, to put elements in ascending numeric order, we could use
a function like this:
function sortAscendingNumbers (element1, element2) {
if (element1 < element2) {
return -1;
} else if (element1 > element2) {
return 1;
} else {
return 0; // The elements are equal
}
}
// Now that our compare function is ready, let's try it out
var x = [34, 55, 33, 1, 100];
x.sort(sortAscendingNumbers);
trace(x); // Displays: "1,33,34,55,100"
Numeric-sort functions can actually be phrased much more succinctly.
The preceding sortAscendingNumbers( ) function
could be written as:
function sortAscendingNumbers (element1, element2) {
return element1 - element2;
}
In our optimized version, a negative number is returned if
element1 is less than element2,
a positive number is returned if element1 is
greater than element2, and a
is returned if the two are equal. Now that's elegant! Here is a
version to perform a descending sort:
function sortDescendingNumbers (element1, element2) {
return element2 - element1;
}