Array.prototype.toSorted()
toSorted(compareFn) Returns:
array · Added in vES2023 · Updated March 13, 2026 · Array Methods array sort immutable
The toSorted() method returns a new array with the elements sorted. It’s the immutable counterpart to sort() — your original array stays untouched, which is essential for React, Redux, and other scenarios where immutability matters.
Syntax
arr.toSorted(compareFn)
Parameters
| Parameter | Type | Description |
|---|---|---|
compareFn | function | Optional function that defines sort order |
The compare function receives two arguments:
a: First element for comparisonb: Second element for comparison
Return negative if a < b, positive if a > b, zero if equal.
Examples
Basic usage (numbers)
const arr = [3, 1, 2];
const sorted = arr.toSorted();
console.log(arr); // [3, 1, 2] (unchanged)
console.log(sorted); // [1, 2, 3]
Descending order
const nums = [5, 2, 8, 1, 9];
const descending = nums.toSorted((a, b) => b - a);
console.log(descending); // [9, 8, 5, 2, 1]
Sorting strings
const words = ['banana', 'apple', 'cherry', 'date'];
const alphabetical = words.toSorted();
console.log(alphabetical); // ['apple', 'banana', 'cherry', 'date']
// Case-insensitive sorting
const mixed = ['Apple', 'banana', 'Cherry', 'date'];
const caseInsensitive = mixed.toSorted((a, b) =>
a.localeCompare(b)
);
console.log(caseInsensitive); // ['Apple', 'banana', 'Cherry', 'date']
Sorting objects by property
const users = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Carol', age: 35 }
];
const byAge = users.toSorted((a, b) => a.age - b.age);
console.log(byAge.map(u => u.name)); // ['Bob', 'Alice', 'Carol']
const byName = users.toSorted((a, b) => a.name.localeCompare(b.name));
console.log(byName.map(u => u.name)); // ['Alice', 'Bob', 'Carol']
Chaining with other methods
const data = [4, 2, 5, 1, 3];
const result = data
.filter(n => n > 2)
.toSorted()
.map(n => n * 2);
console.log(result); // [6, 8, 10]
Sorting with nulls and undefined
const mixed = [3, null, 1, undefined, 2];
// Put nulls/undefined at the end
const sorted = mixed.toSorted((a, b) => {
if (a == null) return 1;
if (b == null) return -1;
return a - b;
});
console.log(sorted); // [1, 2, 3, null, undefined]
Common Mistakes
The default sort converts elements to strings:
[10, 2, 21].sort(); // [10, 2, 21] - wrong!
[10, 2, 21].toSorted(); // [10, 2, 21] - still wrong without compareFn!
[10, 2, 21].toSorted((a, b) => a - b); // [2, 10, 21] - correct
See Also
Array.prototype.toReversed()— Return reversed copy of arrayArray.prototype.with()— Return copy with element replaced at index