JavaScript Array.prototype.sort() Method
The sort() method sorts the elements of an array in place. Without a compare function it sorts as strings, so numbers need a function like (a, b) => a - b.
Description
The sort() method sorts an array in place and returns it. Without a compare function, elements are converted to strings and sorted by UTF-16 code units, which puts 10 before 9 and capital letters before lowercase ones.
Pass a compare function to sort properly: (a, b) => a - b sorts numbers ascending, and (a, b) => a.name.localeCompare(b.name) sorts objects by a text property. The sort is stable, so equal elements keep their original order. Use toSorted() to get a sorted copy instead of changing the original.
Sorting is done in place and the same array is returned, so const sorted = arr.sort() also sorts arr. undefined values are always moved to the end without calling the compare function, and empty slots come after them. For sorting text in a language-aware way, pass new Intl.Collator().compare, which also handles accents and numbers inside text.
Syntax
array.sort()
array.sort(compareFn)Parameters
- compareFnOptional. A function
(a, b)that returns a negative number ifashould come first, a positive number ifbshould, or 0 to keep their order.
Return Value
The same array, now sorted.
Example
Browser Support
The following information will show you the current browser support for the Array.prototype.sort() method. Hover over a browser icon to see the version that first introduced support for this method.
Desktop





Tablets & Mobile





