JavaScript » Array » sort

Syntax:
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.

Examples

Code:
names = ["John", "Andrea", "Charlie", "Sam", "Kate"]
sorted_names = names.sort()
document.write(sorted_names)
Output:
Andrea,Charlie,John,Kate,Sam
Explanation:

This example is a straight-forward sort of an array of names.

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
Explanation:

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.

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
Explanation:

If two numbers are compared, the compareFunction simply needs to subtract the second from the first number.