Array.sort()

Availability

Flash Player 5.

Usage

my_array.sort([compareFunction])

Parameters

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

Returns

Nothing.

Description

Method; sorts the array in place, without making a copy. If you omit the compareFunction parameter, Flash sorts the elements in place using the < comparison operator.

Example

The following example uses Array.sort without specifying the compareFunction parameter:

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

Output:

oranges,apples,strawberries,pineapples,cherries
apples,cherries,oranges,pineapples,strawberries

The following example uses Array.sort with a specified order function.

var passwords_array =[
"gary:foo",
"mike:bar",
"john:snafu",
"steve:yuck",
"daniel:1234"
];
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;
	}
}
for (var i=0;i<passwords_array.length;i++){
	trace (passwords_array.join());
}
passwords_array.sort(order);
trace ("Sorted:");
for (var i=0;i<passwords_array.length;i++){
	trace (passwords_array.join());
}

Running the previous code displays the following result in the Output window.

daniel:1234
gary:foo
john:snafu
mike:bar
steve:yuck