The JavaScript array.sort() method
The sort() method orders an array in place and returns it. By default it sorts elements as strings, which is why [10, 2, 1].sort() surprisingly gives [1, 10, 2]. For numbers, pass a compare function: arr.sort((a, b) => a - b) sorts ascending. It mutates the original array.
Overview
sort() rearranges an array into order and returns that same (now sorted) array. The headline gotcha is the default: with no arguments it converts every element to a string and sorts those, so [10, 2, 1] becomes [1, 10, 2] — because "10" comes before "2" alphabetically. For text that's fine; for numbers it's almost never what you want.
The fix is a compare function. You give sort() a function that takes two elements, a and b, and returns a negative number if a should come first, a positive number if b should, or 0 if they tie. For numbers ascending, (a, b) => a - b is the whole trick; flip it to b - a for descending. For objects, compare a property: (a, b) => a.age - b.age.
Two things to keep in mind: sort() mutates the array, so copy it first with slice() or the spread operator if you need to keep the original; and modern engines make it stable, so equal elements keep their relative order. To reverse an already-sorted array, there's reverse().
Syntax
array.sort() // sorts as strings (watch out for numbers)
array.sort(compareFn)
array.sort((a, b) => a - b) // numbers ascending
array.sort((a, b) => b - a) // numbers descending
Parameters
The array.sort() method accepts the following parameters.
| Parameter | Description |
|---|---|
compareFn |
Optional. Function comparing two elements (a, b). Return a negative number to put a first, positive to put b first, 0 to keep order. Omit it and elements are sorted as strings. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const nums = [10, 2, 33, 4, 1];
const wrong = [...nums].sort(); // string sort
const right = [...nums].sort((a, b) => a - b);
document.getElementById('out').textContent =
'default: ' + wrong.join(', ') + '\n' +
'numeric: ' + right.join(', ');
// default: 1, 10, 2, 33, 4 / numeric: 1, 2, 4, 10, 33
</script>
Best practices
- Always pass a compare function for numbers —
(a, b) => a - b— or the default string sort will mis-order them. - Copy the array first (
[...arr].sort(...)) if you need to keep the original, sincesort()mutates. - Sort objects by a key with
(a, b) => a.value - b.value, orlocaleComparefor strings. - For descending order, swap the operands:
(a, b) => b - a.
Frequently asked questions
Why does sort() put 10 before 2?
"10" sorts before "2". Pass a compare function — (a, b) => a - b — to sort numerically.How do I sort numbers in JavaScript?
arr.sort((a, b) => a - b) for ascending, (a, b) => b - a) for descending.Does sort() change the original array?
[...arr] or slice() if you need the original.How do I sort an array of objects?
users.sort((a, b) => a.age - b.age) for numbers, or a.name.localeCompare(b.name) for text.