METHOD: Array::sort
Array.sort(compareFunction)
The sort method sorts the elements of an array. If no compareFunction argument is supplied,
all the elements are converted into strings and sorted lexicographically (i.e. in
dictionary order). This means, for example, that 30 would come before 4. The following
example is a straight-forward sort of an array of names:
Code:
names = ["John", "Andrea", "Charlie", "Sam", "Kate"]
sorted_names = names.sort()
document.write(sorted_names)
Output:
Andrea,Charlie,John,Kate,Sam
By including a compareFunction argument, you can define the sort order. Two array elements are
sorted according to the return value of the compare function:
if it is 0, the order of the two elements remains unchanged;
if it is greater than 0, the first of the two elements is sorted to a higher index
than the second; and if it is less than 0,
the second element is sorted to a higher index than the first.
The following code creates an array called 'trees' and then,
using the user-defined function 'reverseSort', displays the elements sorted in reverse order:
Code:
trees = ["oak", "ash", "beech", "maple", "sycamore"]
function reverseSort(a, b)
{
if(a > b)
return -1
if(a < b)
return 1
return 0
}
document.write(trees.sort(reverseSort))
Output:
sycamore,oak,maple,beech,ash
If two numbers are compared, the compareFunction simply needs to subtract the second
from the first number:
Code:
ages = [30, 25, 47, 19, 21, 8]
function sortNumbers(a, b) { return a - b}
document.write(ages.sort(sortNumbers))
Output:
8,19,21,25,30,47
|