CKTIS / JavaScript
Array.prototype.toSorted: a stably sorted copy
toSorted stably sorts a new dense array while leaving the receiver and its original order unchanged.
Version: ECMAScript 2023; stable ordering required; example target: Node.js 24.22.2
Syntax
array.toSorted(compareFn?)array.toSorted(compareFn?) returns a new ordinary Array whose values are stably ordered, without mutating array. compareFn(a, b) follows sort(): a negative result places a earlier, a positive one later, and zero or NaN retains the order of equal values. The callback never receives undefined.
Without a callback, non-undefined values are compared as strings by UTF-16 code units. undefined is placed last. Receiver holes are read as undefined, so the result is dense. The method ignores Symbol.species and makes a shallow copy of references.
It is generic for array-like values. A non-callable callback or a null or undefined receiver throws TypeError; conversion, reads, callback, and proxy failures propagate, while a length too large for an ordinary Array can produce RangeError. The API was standardized in ECMAScript 2023.
Examples
const tasks = [
{ label: "deploy", priority: 2 },
{ label: "test", priority: 1 },
{ label: "docs", priority: 2 },
];
const ordered = tasks.toSorted((a, b) => a.priority - b.priority);
console.log(ordered.map(item => item.label).join(","));
console.log(tasks.map(item => item.label).join(","));
console.log([80, 9, 100].toSorted().join(","));
const dense = [3, , 1].toSorted((a, b) => a - b);
console.log(dense.length, 0 in dense, 1 in dense, 2 in dense, dense[0], dense[1], String(dense[2]));Result
test,deploy,docs deploy,test,docs 100,80,9 3 true true true 1 3 undefined