JavaScript Reference Β· Array
Array.prototype.sort()
Reference for JavaScript Array.prototype.sort(): sort in place, why the default order is alphabetical, writing comparators, stable sorting and the toSorted() copy.
The sort() method sorts the elements of an array in place and returns the same array. Without arguments it converts every element to a string and compares them by UTF-16 code units, which is why numbers sort in surprising ways. To sort by something else, pass a comparator function.
Sorting is stable: elements that compare as equal keep their relative order. That makes multi-step sorts (sort by name, then by group) reliable.
const names = ["Bo", "Al", "Cy"]; names.sort(); // ["Al", "Bo", "Cy"]
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
array.sort() array.sort(compareFn)
| Name | Description |
|---|---|
compareFn |
Optional. Called as compareFn(a, b). Return a negative number if a should come before b, a positive number if a should come after b, and 0 if they are equal. |
Return value: the same array, now sorted (not a copy).
Exceptions: a TypeError if compareFn is given and is not a function or undefined, or if the array is frozen.
Usage notes
- It mutates. Copy first (
[...array].sort()) or usetoSorted()to keep the original. - The default is lexicographic.
[10, 9, 1].sort()gives[1, 10, 9]. Always pass a comparator for numbers:(a, b) => a - b. - Comparator rules. It must be consistent: the same inputs give the same answer, and it should not return
NaNor booleans. A function returninga > bappears to work in some engines and breaks in others, becausetrue/falsemap to1/0and never give a negative result. - Subtraction can overflow or mislead with huge numbers,
InfinityorNaN. For arbitrary values, return explicit-1,0,1comparisons. undefinedgoes last, and holes after that, without calling the comparator for them.- Human text order: use
a.localeCompare(b)orIntl.Collatorso accents and case are handled according to a language. The default code-unit order puts all capitals before lowercase letters. - Stable. Equal elements keep their original order in all current engines (guaranteed since ES2019).
- Sort by several keys by chaining with
||:a.last.localeCompare(b.last) || a.first.localeCompare(b.first). - Descending order is a flipped comparator,
(a, b) => b - a. Sorting ascending and then callingreverse()also works, but it reverses the order of equal items too. - Cost. Sorting is O(n log n). Do it once, not inside a render loop.
- Generic. It also works on array-likes via
Array.prototype.sort.call(obj).
Browser support
Array.prototype.sort() works everywhere. Guaranteed stability arrived in ES2019 and applies to all current browsers; very old engines may differ. The non-mutating toSorted() is newer, so check a compatibility table.