Array.sort()

Availability

Flash Player 5; additional capabilities added in Flash Player 7.

Usage

my_array.sort()
my_array.sort(compareFunction)
my_array.sort(option | option |... )
my_array.sort(compareFunction, option | option |... )

Parameters

compareFunction An optional comparison function used to determine the sorting order of elements in an array. Given the elements A and B, the result of compareFunction can have one of the following three values:

option One or more numbers or strings, separated by the | (bitwise OR) operator, that change the behavior of the sort from the default. The following values are acceptable for option:

For information on this parameter, see Array.sortOn().

Returns

The return value depends on whether you pass any parameters:

Description

Method; sorts the elements in an array. Flash sorts according to ASCII (Unicode) values. If either of the elements being compared does not contain the field specified in the fieldName parameter, the field is assumed to be undefined, and the elements are placed consecutively in the sorted array in no particular order.

By default, Array.sort() works as follows:

If you want to sort in another way, create a function to do the sorting and pass its name as the compareFunction parameter. You might do this, for example, if you want to sort alphabetically by last name, ascending, and then by ZIP code, descending.

If you want to specify one or more fields on which to sort, using either the default sort or the options parameter, use Array.sortOn().

Example

Usage 1: The following example shows the use of Array.sort() with and without a value passed for option:

var fruits_array = ["oranges", "apples", "strawberries", "pineapples", "cherries"];
trace(fruits_array.join());
fruits_array.sort();
trace(fruits_array.join());
fruits_array.sort(Array.DESCENDING);
trace(fruits_array.join());

The Output panel displays the following results:

oranges,apples,strawberries,pineapples,cherries  // original array
apples,cherries,oranges,pineapples,strawberries  // default sort
strawberries,pineapples,oranges,cherries,apples  // descending sort

Usage 2: The following example uses Array.sort() with a compare function.

var passwords = ["mom:glam","ana:ring","jay:mag","anne:home","regina:silly"];
function order (a,b){
  //Entries to be sorted are in form name:password
  //Sort using only the name part of the entry as a key.
  var name1 =a.split(":")[0 ];
  var name2 =b.split(":")[0 ];
  if (name1 <name2){
    return -1;
  }
  else if (name1 >name2){
    return 1;
  }
  else {
    return 0;
  }
}
trace ("Unsorted:");
trace (passwords.join());

passwords.sort(order);
trace ("Sorted:");
trace (passwords.join());

The Output panel displays the following results:

Unsorted:
mom:glam,ana:ring,jay:mag,anne:home,regina:silly
Sorted:
ana:ring,anne:home,jay:mag,mom:glam,regina:silly

See also

| (bitwise OR), Array.sortOn()