Array.prototype.sort
Sorts the elements of an array.
Available since: ES1
Syntax
array.sort(compareFn)Parameters
| Parameter | Type | Description |
|---|---|---|
| compareFn | Function | Optional. A function comparing two elements: a negative number puts the first one earlier, a positive number later. |
Return value
ArrayThe same array, sorted in place.
Examples
Sorting strings:
console.log(['pear', 'apple', 'plum'].sort().join(', '));Output:
apple, pear, plumWithout a comparison function numbers are sorted as strings:
console.log([10, 9, 1].sort().join(', '));
console.log([10, 9, 1].sort((a, b) => a - b).join(', '));Output:
1, 10, 9
1, 9, 10Notes
The method modifies the array itself. To keep the original order, sort a copy: [...array].sort().
See also
- Array.prototype.slice — Returns part of an array.
- Array.prototype.map — Creates a new array by transforming every element.
- Array.prototype.toSorted — Returns a sorted copy of an array without changing the original.
- String.prototype.localeCompare — Compares strings by language rules — for alphabetical sorting.
- Array.prototype.reverse — Reverses an array in place.
Related recipes
In the tutorial
- Sorting arrays — How to sort an array in JavaScript: sort, the compare function, sorting numbers, strings and objects, reverse and toSorted.