Array.sort method

JavaScript FAQ | JavaScript Arrays FAQ  

Question: Why does [10,11,1,2].sort() return [1,10,11,2]?

Answer: The array.sort() method, when called without parameters, sorts the elements of the array in alphabetical order (or lexicographical order). If some or all of the array elements are not strings, they are temporarily converted to strings, and then the array is alphabetically sorted. In the above example, [10,11,1,2].sort() returns [1,10,11,2] because thatís the correct alphabetical order of the strings '1', '10', '11', '2'.

If you need ascending number sorting, descending number sorting or, generally speaking, any sorting other than alphabetical, then you must supply your own sort order function (sometimes also called comparison function) as a parameter to array.sort(). The sort order function should take two arguments and return

  • a negative number if the first argument should precede the second in the sorted array,
  • a positive number if the second argument should precede the first in the sorted array, and
  • 0 if the two arguments are deemed equal for sorting purposes.
Here are order functions you can use for ascending and descending number sorting:
function AscendingNumberSort (a,b) {return a-b;}
function DescendingNumberSort(a,b) {return b-a;}

[10,11,1,2].sort(AscendingNumberSort)   // result: 1,2,10,11
[10,11,1,2].sort(DescendingNumberSort)  // result: 11,10,2,1

See also:
Deleting an array element

Copyright © 1999-2011,