JavaScript (ES2026) reference · Array Methods
JavaScript Array sort() Method
Sort the array in place and return it. Without a compare function elements are sorted as strings, so numbers need one.
JavaScript (ES2026) Since ES1
Syntax
array.sort(compareFn)
Parameters
| Parameter | Description |
|---|---|
compareFn optional |
Returns a negative number if a comes first, positive if b does, 0 if equal. |
Return value
The same, sorted array.
Examples
console.log([10, 9, 1, 100].sort()); // compared as strings!
console.log([10, 9, 1, 100].sort((a, b) => a - b));
Output
[ 1, 10, 100, 9 ] [ 1, 9, 10, 100 ]
const people = [{ name: "Linus", age: 28 }, { name: "Ada", age: 36 }];
people.sort((a, b) => a.name.localeCompare(b.name));
console.log(people.map((p) => p.name));
Output
[ 'Ada', 'Linus' ]
const original = [3, 1, 2];
const sorted = original.toSorted((a, b) => a - b);
console.log(original, sorted);
Output
[ 3, 1, 2 ] [ 1, 2, 3 ]
Common mistakes
- Without a compare function,
[10, 9, 1].sort()gives[1, 10, 9]: elements are compared as strings. Use(a, b) => a - bfor numbers. sort()changes the array. UsetoSorted()(ES2023) or sort a copy ([...arr].sort()).- The sort is stable (guaranteed since ES2019).
Version history
| Version | Change |
|---|---|
| JavaScript ES1 | Added |
| JavaScript ES2019 | The sort is guaranteed to be stable. |
In other languages
list.sort()· Python
Related
array.toSorted()· Return a new sorted array, leaving the original unchanged. Takes the same compare function as sort().array.reverse()· Reverse the array in place and return it. Use toReversed() to get a reversed copy instead.- JavaScript Arrays · tutorial
- JavaScript Array Methods · tutorial