
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
General Array-Manipulation Tools
|
265
The sort() and sortOn() Methods
The sort() method rearranges elements in an array according to an arbitrary rule that
we provide. If we provide no rule, sort() places the elements in (roughly) alphabeti-
cal order by default. Sorting an array alphabetically is really easy, so let’s first see
how that works:
arrayName.sort()
When we invoke an array’s sort() method with no arguments, its elements are tem-
porarily converted to strings and sorted according to their Unicode code points
(equivalent to ASCII values for code points below 128). For the code points of most
western European languages, see Appendix B. See also “Character order and alpha-
betic comparisons” in Chapter 4 for important details.
// 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.
We can also use sort() to organize array elements according to a rule of our own
choosing. This technique is a little trickier to work with, but it’s quite powerful. We