Array.sort method

JavaScript FAQ | JavaScript Arrays FAQ  

Question: Why does


Answer: The

method, when called without parameters, sorts the elements of the array in alphabetical order (or lexicographical order). If some or all of the
elements are not strings, they are temporarily converted to strings, and then the array is alphabetically sorted. In the above example,
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

. 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 © 1996-2018,