sort (JavaScript)

Sorts the elements of an array.

Defined in

Array (Standard - JavaScript)

Syntax

sort(comparefn:java.lang.Object) : Array (Standard - JavaScript)
Parameters Description
comparefn A function for making the comparisons. The function takes two parameters and returns: a negative number if the first parameter is less than the second, 0 if the parameters are equal, or a positive number if the first parameter is greater than the second. If the function is null or omitted, the sort is alphabetic.
Return value Description
Array The sorted array.

Usage

Elements that compare equal may not be in the same order in the sorted array as in original array.

The default alphabetic sort treats everything, including numbers, as strings. To sort by numeric value, you must provide the parameter. See the examples.

Examples

(1) This computed label sorts an array alphabetically.
var a = new Array("one", "two", "three", "four");
a.sort() // [four, one, three, two]
(2) This computed label sorts an array numerically by providing a function to do the compare.
function sortn(x, y) {
	if (x < y) return -1;
	else if (x == y) return 0;
	else return 1;
}
var a = new Array(40, 6, 101, 3003, 2, 5);
a.sort(sortn) // [2.0, 5.0, 6.0, 40.0, 101.0, 3003.0]
(3) This computed label shows what happens if you do not use a function for numbers.
var a = new Array(40, 6, 101, 3003, 2, 5);
a.sort() // [101.0, 2.0, 3003.0, 40.0, 5.0, 6.0]