Array. prototype. sort()
Sorts the array’s elements in place and returns the same array.
- Returns
- The same, sorted array.
- Changes the original
- Yes
Example
#const numbers = [10, 9, 1, 25]
console.log([...numbers].sort())
console.log([...numbers].sort((a, b) => a - b))
console.log([...numbers].sort((a, b) => b - a))Definition and usage
#The sort() method arranges the array’s elements according to the comparator function you give it. It changes the original and returns a reference to that same array.
Without a comparator, elements are converted to strings and sorted alphabetically by character code. That’s why [10, 9, 1].sort() gives [1, 10, 9]. Always sort numbers with the function (a, b) => a - b.
The comparator returns a negative number when a should come before b, a positive one when it should come after, and zero when the order doesn’t matter. For strings with accented characters, use localeCompare().
Syntax
#array.sort()
array.sort(compareFn)Parameters
#compareFn
function (a, b)
The comparator function. A negative result placesabeforeb.
More examples
#const students = [
{ name: 'Zoe', points: 90 },
{ name: 'Amy', points: 120 },
{ name: 'Noah', points: 90 }
]
const byName = [...students].sort((a, b) => a.name.localeCompare(b.name, 'en'))
console.log(byName.map((s) => s.name))Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Always sort numbers with the function
(a, b) => a - b. The default sort treats them as text. - If you don’t want to change the original, use
toSorted()or sort a copy:[...array].
Related entries
#- Array.prototype.toSorted()Returns a sorted copy of the array, leaving the original unchanged.
- Array.prototype.reverse()Reverses the order of the array’s elements in place.
- String.prototype.localeCompare()Compares two strings according to language rules. Returns a negative number, zero, or a positive number, perfect for sorting.
Spotted a mistake or missing an example? Write to us.