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.
names = ["John", "Andrea", "Charlie", "Sam", "Kate"]
sorted_names = names.sort()
document.write(sorted_names)
Andrea,Charlie,John,Kate,Sam
This example is a straight-forward sort of an array of names.
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))
sycamore,oak,maple,beech,ash
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. This code creates an array called 'trees' and then, using the user-defined function 'reverseSort', displays the elements sorted in reverse order.
ages = [30, 25, 47, 19, 21, 8]
function sortNumbers(a, b) { return a - b}
document.write(ages.sort(sortNumbers))
8,19,21,25,30,47
If two numbers are compared, the compareFunction simply needs to subtract the second from the first number.