Array.prototype.toSorted(): sort a copy (ES2023)
What you’ll learn
Section titled “What you’ll learn”- How
toSorted()differs fromsort(), and why that matters for shared state. - How comparators work, and why the default order surprises people with numbers.
- What happens to
undefined, holes and equal keys. - How to build multi-key, locale-aware sorts, and when
sort()is still better.
Summary
Section titled “Summary”TL;DR: array.toSorted(compareFn?) returns a new, sorted array and leaves array unchanged. It takes the same optional comparator as sort() and sorts the same way: stably, with the same default order.
It was added in ECMAScript 2023 by the “Change Array by Copy” proposal, alongside toReversed(), toSpliced() and with(). It is supported in all current browsers and Node.js 20+ (see Compatibility).
The problem it solves
Section titled “The problem it solves”sort() sorts in place and returns the same array, so sorting props, state or a cached response changes it for every other reader. Forgetting the defensive copy, [...arr].sort(fn), was a classic bug.
Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs). All outputs shown were produced with Node.js 22.23. The examples use an invented order-management app, OrdersPortal.
const totals = [120, 45, 300];
// Before: sort() mutates, so you had to copy first.const copySorted = [...totals].sort((a, b) => a - b);// Forgetting the copy silently reorders the caller's array:const oops = totals.sort((a, b) => b - a);console.log(oops === totals, totals);
// After: toSorted() copies and sorts in one step.const amounts = [120, 45, 300];const ascending = amounts.toSorted((a, b) => a - b);console.log(amounts, ascending, copySorted);Output:
true [ 300, 120, 45 ][ 120, 45, 300 ] [ 45, 120, 300 ] [ 45, 120, 300 ]How it works
Section titled “How it works”// Fragment: signatureconst sorted = array.toSorted(compareFn);// compareFn(a, b) returns < 0 if a comes first, > 0 if b comes first, 0 to keep their orderFrom the specification:
- The comparator is checked first. Anything other than a function or
undefinedthrows aTypeErrorbefore any work is done. - No comparator means string order. Values are converted to strings and compared by UTF-16 code units, so
10sorts before9and'C'before'a'. undefinedand holes go last, without being passed to the comparator. Holes come back asundefined, so the result is dense.- The sort is stable. Equal elements keep their relative order (required since ES2019; both methods share the algorithm).
- The result is a new, shallow, plain
Array, even for a subclass or array-like receiver. - Typed arrays have their own
toSorted(), which sorts numerically by default and returns the same typed array type.
console.log([10, 9, 1, 100].toSorted());console.log([10, 9, 1, 100].toSorted((a, b) => a - b));console.log(['b', 'a', 'C', 'É'].toSorted());
console.log([3, undefined, 1, , 2].toSorted((a, b) => a - b));
const orders = [ { id: 'o-1', status: 'paid' }, { id: 'o-2', status: 'open' }, { id: 'o-3', status: 'paid' }, { id: 'o-4', status: 'open' },];console.log(orders.toSorted((a, b) => a.status.localeCompare(b.status)).map((o) => o.id));
try { [2, 1].toSorted('desc'); } catch (e) { console.log(e.constructor.name + ':', e.message); }
console.log(new Float64Array([10, 9, 1, 100]).toSorted());console.log(Array.prototype.toSorted.call({ length: 2, 0: 'b', 1: 'a' }));Output (the TypeError message is V8’s wording):
[ 1, 10, 100, 9 ][ 1, 9, 10, 100 ][ 'C', 'a', 'b', 'É' ][ 1, 2, 3, undefined, undefined ][ 'o-2', 'o-4', 'o-1', 'o-3' ]TypeError: The comparison function must be either a function or undefined: descFloat64Array(4) [ 1, 9, 10, 100 ][ 'a', 'b' ]The stable sort is visible in the fifth line: within open and paid, the orders keep their input order.
Realistic example
Section titled “Realistic example”The OrdersPortal order table sorts by customer, total or date, keeps priority orders on top, and breaks ties by date. The source list is a shared cache and must never be reordered.
const orders = [ { id: 'o-101', customer: 'Zoë Park', total: 120.5, placedAt: '2026-11-02T09:15:00Z', priority: false }, { id: 'o-102', customer: 'ana Ruiz', total: 45, placedAt: '2026-11-03T14:00:00Z', priority: true }, { id: 'o-103', customer: 'Émile Roy', total: 300, placedAt: '2026-11-01T08:30:00Z', priority: false }, { id: 'o-104', customer: 'Ben Ode', total: 45, placedAt: '2026-11-03T10:45:00Z', priority: true },];
const byName = new Intl.Collator('en', { sensitivity: 'base' });const comparators = { customer: (a, b) => byName.compare(a.customer, b.customer), total: (a, b) => a.total - b.total, placedAt: (a, b) => Date.parse(a.placedAt) - Date.parse(b.placedAt),};
// Sort by a column, then by placedAt as a tie-breaker. Priority orders always first.function sortedView(list, column, direction = 'asc') { const sign = direction === 'asc' ? 1 : -1; return list.toSorted((a, b) => Number(b.priority) - Number(a.priority) || sign * comparators[column](a, b) || comparators.placedAt(a, b));}
console.log(sortedView(orders, 'customer').map((o) => o.customer));console.log(sortedView(orders, 'total', 'desc').map((o) => `${o.id} ${o.total}`));console.log(orders.map((o) => o.id)); // source order unchangedOutput:
[ 'ana Ruiz', 'Ben Ode', 'Émile Roy', 'Zoë Park' ][ 'o-104 45', 'o-102 45', 'o-103 300', 'o-101 120.5' ][ 'o-101', 'o-102', 'o-103', 'o-104' ]Intl.Collator sorts names as users expect (case-insensitive, É next to E), and one reused collator is faster than localeCompare with options on every comparison. Chaining with || gives multi-key sorting, because a tie (0) falls through to the next key. The direction flips only the column comparison, so the priority group and date tie-breaker are unaffected.
Common mistakes
Section titled “Common mistakes”- Sorting numbers without a comparator.
[10, 9, 1].toSorted()is[1, 10, 9]. Pass(a, b) => a - b. - Returning a boolean.
(a, b) => a > breturnstrue/false, which convert to1/0and never signal “a comes first”. The result depends on the engine’s algorithm; in V8[3, 1, 2].toSorted((a, b) => a > b)returns[3, 1, 2]unchanged. Return a negative, zero or positive number. - Shuffling with a random comparator.
() => Math.random() - 0.5is inconsistent and does not shuffle uniformly; use a Fisher-Yates shuffle. - Expecting a deep copy. The new array holds the same objects; editing
sorted[0].nameedits the original element. - Sorting on every render. Each call allocates; memoize the sorted view on the list and sort key.
toSorted().toReversed()for descending order. That makes two copies and turns a stable ascending sort into a reverse-stable one: ties end up in reverse input order. Invert the comparator instead.
When to use it and when not to
Section titled “When to use it and when not to”| Situation | Use |
|---|---|
| The array is props, state, a cache entry or a function argument | toSorted() |
| A local array you just built and nobody else references | sort() (sorts in place, no second array) |
| A very large array where memory matters and mutation is safe | sort() |
| Only the top few items are needed from a huge list | a single pass or a heap, not a full sort |
| Reverse without sorting | toReversed() |
| Sort an object’s entries | Object.entries(obj).toSorted(...) |
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, Array.prototype.toSorted and TypedArray.prototype.toSorted are supported in Chrome 110, Edge 110, Firefox 115, Safari 16 (including iOS), Node.js 20.0.0, Deno 1.31 and Bun 1.0. Internet Explorer never supported them.
TypeScript: the typings are in lib.es2023.array.d.ts. With an older lib or target, TypeScript 6.0 reports Property 'toSorted' does not exist on type 'number[]' and suggests es2023 or later. TypeScript does not polyfill it; for Node.js 18 or older browsers use core-js, or [...arr].sort(fn), which gives the same result (spread also turns holes into undefined).
Interview questions
Section titled “Interview questions”1. Why does [10, 9, 1].toSorted() return [1, 10, 9]?
Without a comparator, elements are converted to strings and compared by UTF-16 code units, and '10' comes before '9'. Pass (a, b) => a - b for numbers. Typed arrays are the exception: their toSorted() sorts numerically by default.
2. Is toSorted() stable, and why does that matter?
Yes: equal elements keep their input order. That keeps table rows from jumping when users sort a column with many ties, and lets you sort by a secondary key, then the primary key.
3. What happens to undefined values and holes?
They are moved to the end without calling the comparator, and holes come back as undefined. To control where missing values go (for example, missing dates first), represent them as null or another sentinel: unlike undefined, those are passed to the comparator, which can then place them explicitly.
4. Senior scenario: a dashboard sorts 100,000 rows client-side with toSorted() on every keystroke in a filter box, and typing lags. How do you fix it?
Filter first, then sort the smaller result, and memoize the sorted view on data, filter and sort key. Make the comparator cheap: reuse one Intl.Collator and precompute keys such as parsed dates instead of calling Date.parse in every comparison. If it is still too slow, debounce the input, sort on the server, or move sorting to a worker.
Key takeaways
Section titled “Key takeaways”toSorted()(ES2023) issort()without the mutation: same comparator, same stable algorithm.- The default order is string order; always pass a comparator for numbers.
undefinedand holes go last; the result is a dense, plain, shallow copy.- Use
Intl.Collatorfor names and||chains for multi-key sorts. - Prefer
sort()only for arrays you own outright.
Related pages
Section titled “Related pages”- Array.prototype.toReversed: reverse a copy.
- Array.prototype.with: replace one element in a copy.
- Array.from: turn iterables such as
SetorMapinto sortable arrays. - Object.entries: sort an object’s key-value pairs.
- Arrays (basics)
Official references
Section titled “Official references”- ECMAScript Language Specification,
Array.prototype.toSorted ( comparator )(current draft; first published in ECMAScript 2023) - ECMAScript 2023 Language Specification (ECMA-262, 14th edition)
- TC39 proposal: Change Array by Copy
- MDN: Array.prototype.toSorted()
- MDN: Array.prototype.sort()
- MDN: Intl.Collator