Array.sort( ) Method | Flash 5 |
sort the elements of an array |
An optional function that dictates how to sort array.
When invoked without the optional compareFunction argument, sort( ) temporarily converts the elements of array to strings and orders the elements according to the Unicode code points of those strings (approximately alphabetical order for Western European languages). Alphabetic comparisons and code points are described in Section 4.6.2.2 in Chapter 4.
When invoked with a compareFunction argument, sort( ) reorders the elements of array according to the return value of compareFunction, which is a user-defined function that dictates how to sort any two values in the array. Your user-defined compareFunction should be designed to accept two array elements as arguments. It should return a negative number if the first element should come before the second element; it should return a positive number if the first element should come after the second element; and it should return a 0 if the elements should not be reordered. If additional elements are added to the array after it has been sorted, they are not added in sorted order. You must resort the array to reorder any newly added elements. Note that numbers are sorted according to their Unicode code points by default (which are the same code points as Latin 1 and ASCII). Chapter 11 explains how to sort numbers by their numeric values. To ensure case-insensitive alphabetic sorting for Latin 1 letters, use String.toUpperCase( ) to convert strings to uppercase before calling sort( ) or inside the compareFunction, as shown in Example 11-6.
To sort a group of objects by a given property's value, use the sortOn( ) method.
In Flash Player 5, Array.sort( ) has several sorting errors, described at: http://moock.org/asdg/technotes/arraySortBugs. These are fixed in Flash Player 6.
The following example sorts an array of movie clips according to their horizontal location on screen. This is useful to create a fade effect that travels from left to right across the screen and fades the movie clips based on their position, even if that position changes dynamically.
var clips = [clip1, clip2, clip3, clip4]; function compareXposition (element1, element2) { if (element1._x < element2._x) { return -1; } else if (element1._x > element2._x) { return 1; } else { return 0; // The clips have the same x position } } clips.sort(compareXposition);
Array.reverse( ), Array.sortOn( ); "The sort( ) and onsort( ) Methods," in Chapter 11