Browse topics

Array.prototype.toSorted

Version
es2025
Since
es2023
Review
Draft

Summary#

toSorted returns a sorted copy of an array, and toReversed returns a reversed copy. The original order stays intact.

Syntax#

js
const sorted = array.toSorted((a, b) => comparison);
const reversed = array.toReversed();

Example#

js
const sizes = [10, 2, 33];

console.log(sizes.toSorted().join(","));
console.log(sizes.toSorted((a, b) => a - b).join(","));
console.log(sizes.toReversed().join(","));
console.log(sizes.join(","));

Expected output#

Text
10,2,33
2,10,33
33,2,10
10,2,33

Common mistakes#

Without a comparator, values are compared as strings, so 10 sorts before 2. Pass (a, b) => a - b for ordinary numbers. The copy is shallow. Missing indexed properties become explicit undefined entries.

Version applicability#

ES2023 added both methods. For dense ordinary arrays on ES2019–ES2022, copy first with array.slice(), then call sort or reverse on the copy. Use a polyfill if you need matching behavior for sparse arrays.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0