O'Reilly logo

Actionscript Cookbook by Joey Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.10. Sorting or Reversing an Array

Problem

You want to sort the elements of an array.

Solution

Use the sort( ) method. For arrays of objects, you can also use the sortOn( ) method.

Discussion

You can perform a simple sort on an array using the sort( ) method. The sort( ) method, without any parameters, sorts the elements of an array in ascending order. Elements are sorted according to the Unicode code points of the characters in the string (roughly alphabetical for Western European languages). However, the sort is also case-sensitive, and it sorts numbers “alphabetically” instead of numerically. See Recipe 6.11 for details on creating custom sorting algorithms that are case-insensitive.

words = ["tricycle", "relative", "aardvark", "jargon"];
words.sort(  );
trace(words);   // Displays: aardvark,jargon,relative,tricycle

The reverse( ) method reverses the order of the elements in an array:

words = ["tricycle", "relative", "aardvark", "jargon"];
words.reverse(  );
trace(words);   // Displays: jargon,aardvark,relative,tricycle

If you want to sort the elements of an array in descending order, use the sort( ) method followed by the reverse( ) method:

words = ["tricycle", "relative", "aardvark", "jargon"];
words.sort(  );
words.reverse(  );
trace(words); // Displays: tricycle,relative,jargon,aardvark

You can sort arrays of objects using the sortOn( ) method. The sortOn( ) method requires a string parameter specifying the name of the property on which to sort the elements:

cars = new Array( ); cars.push({make: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required