General Array-Manipulation Tools

Earlier we saw how array methods can be used to remove elements from and add elements to arrays. ActionScript also offers built-in methods for reordering and sorting elements, converting array elements to strings, and extracting arrays from other arrays.

The reverse( ) Method

As its name suggests, the reverse( ) method reverses the order of the elements of an array. Simple, but impressive. Here’s the syntax:

                  arrayName.reverse( )

And here are the impressive results:

var x = [1, 2, 3, 4];
x.reverse( );
trace(x);  // Displays: "4,3,2,1"

We typically use reverse( ) to reorder a sorted list. For example, if we have a list of products sorted by ascending price, we can display them from least to most expensive, or we can reverse the list to display them from most to least expensive.

Reader Exercise: Try to write your own custom function to reverse the elements in an array. Not only is it harder than it looks, you’ll most likely find that the built-in reverse( ) method is substantially faster.

The sort( ) Method

The sort( ) method rearranges the sequence of elements in an array according to an arbitrary rule that we provide. If we provide no rule, sort( ) places the elements in (roughly) alphabetical order by default. Sorting an array alphabetically is really easy, so let’s see how that works first:

                  arrayName.sort( )

When we invoke an array’s sort( ) method with no arguments, its elements are temporarily converted to strings and sorted according to their code ...

Get ActionScript: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.