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: ...

Get Actionscript Cookbook 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.