Array.prototype.toSorted
Returns a sorted copy of an array without changing the original.
Available since: ES2023
Syntax
array.toSorted(compareFn)Parameters
| Parameter | Type | Description |
|---|---|---|
| compareFn | Function | Optional. A function that compares two elements and returns a negative number, zero or a positive number. |
Return value
ArrayA new sorted array.
Examples
The original array stays the same:
const prices = [30, 5, 120];
const sorted = prices.toSorted((a, b) => a - b);
console.log(sorted.join(', '));
console.log(prices.join(', '));Output:
5, 30, 120
30, 5, 120Sorting objects by name:
const users = [{ name: 'Oleg' }, { name: 'Anna' }];
console.log(users.toSorted((a, b) => a.name.localeCompare(b.name)).map((u) => u.name).join(', '));Output:
Anna, OlegNotes
Without a compare function elements are compared as strings, so [10, 9].toSorted() gives [10, 9]. For numbers always pass (a, b) => a - b.
See also
- Array.prototype.sort — Sorts the elements of an array.
- Array.prototype.toReversed — Returns a reversed copy of an array.
- String.prototype.localeCompare — Compares strings by language rules — for alphabetical sorting.
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.