Sub topic 6
toSorted, toReversed, toSpliced, and with
This chapter assumes you already know the difference between primitives and references, can make shallow copies with spread, and use map and filter to transform arrays without mutation. You should also be comfortable running JavaScript in Node.js 20 or later, or in a current browser. Every example below runs in those environments without a build step.
The Gap These Methods Fill
map, filter, slice, and concat already return new arrays. Four common operations did not have copying versions until recently: sorting, reversing, splicing, and replacing one element by index. Each one changes the array in place:
sort()reorders the original array and returns that same array.reverse()flips the original array and returns that same array.splice()removes or inserts elements in the original and returns the removed elements.arr[i] = valueoverwrites a slot in the original.
Before ES2023 the usual fix was to copy first, then mutate the copy: [...arr].sort(). That works, but it is easy to forget the copy, and a missing [...] is hard to spot in review. The "Change Array by Copy" proposal, standardized in ES2023, added four methods that do the copying for you: toSorted, toReversed, toSpliced, and with.
The Four Methods at a Glance
| Mutating form | Copying form | Returns | Notable difference |
|---|---|---|---|
| `arr.sort(compareFn)` | `arr.toSorted(compareFn)` | New sorted array | Same comparator rules and same default string ordering |
| `arr.reverse()` | `arr.toReversed()` | New reversed array | None beyond copying |
| `arr.splice(start, deleteCount, ...items)` | `arr.toSpliced(start, deleteCount, ...items)` | New array with the edit applied | Does not return the removed items |
| `arr[index] = value` | `arr.with(index, value)` | New array with one slot replaced | Accepts negative indices; throws on out-of-range |
Here they are side by side:
const nums = [3, 1, 2];
const sorted = nums.toSorted(); // [1, 2, 3]
const reversed = nums.toReversed(); // [2, 1, 3]
const spliced = nums.toSpliced(1, 1); // [3, 2]
const replaced = nums.with(0, 9); // [9, 1, 2]
console.log(nums); // [3, 1, 2], the original is untouched
console.log(sorted, reversed, spliced, replaced);toSorted
toSorted(compareFn) takes the same optional comparator as sort. Without one, it converts elements to strings and compares them in UTF-16 code unit order. That default catches people with numbers, and the copying version keeps the same behavior:
const scores = [10, 1, 2, 25];
console.log(scores.toSorted()); // [1, 10, 2, 25], string order
console.log(scores.toSorted((a, b) => a - b)); // [1, 2, 10, 25], numeric order
console.log(scores); // [10, 1, 2, 25]Sorting objects by a field works the same way. The result is a new array, but the objects inside it are the same objects as in the original:
const users = [
{ name: 'Grace', age: 45 },
{ name: 'Ada', age: 36 }
];
const byName = users.toSorted((a, b) => a.name.localeCompare(b.name));
console.log(byName[0].name); // 'Ada'
console.log(byName === users); // false, a new array
console.log(byName[0] === users[1]); // true, the same object reusedThe sort is stable, just like sort has been since ES2019. Elements that compare as equal keep their original relative order.
toReversed
toReversed() takes no arguments and returns the elements in reverse order. A common use is rendering newest-first from a list stored oldest-first, without touching the stored list:
const history = ['created', 'edited', 'published'];
const newestFirst = history.toReversed();
console.log(newestFirst); // ['published', 'edited', 'created']
console.log(history); // ['created', 'edited', 'published']toSpliced
toSpliced(start, deleteCount, ...items) applies the same edit as splice to a copy. The arguments behave identically:
startcan be negative, counting from the end.- If you omit
deleteCount, everything fromstartto the end is removed. - Any extra arguments are inserted at
start.
const steps = ['plan', 'build', 'test', 'ship'];
const inserted = steps.toSpliced(2, 0, 'review'); // insert without removing
const removed = steps.toSpliced(1, 1); // remove 'build'
const swapped = steps.toSpliced(1, 2, 'prototype'); // replace two with one
const truncated = steps.toSpliced(2); // drop from index 2 on
const lastGone = steps.toSpliced(-1, 1); // remove the last item
console.log(inserted); // ['plan', 'build', 'review', 'test', 'ship']
console.log(removed); // ['plan', 'test', 'ship']
console.log(swapped); // ['plan', 'prototype', 'ship']
console.log(truncated); // ['plan', 'build']
console.log(lastGone); // ['plan', 'build', 'test']
console.log(steps); // ['plan', 'build', 'test', 'ship']The return value is the main difference. splice returns the removed elements. toSpliced returns the new array, so the removed elements are not available from the call. If you need both, use slice to read them:
const queue = ['a', 'b', 'c', 'd'];
const taken = queue.slice(0, 2); // ['a', 'b']
const rest = queue.toSpliced(0, 2); // ['c', 'd']
console.log(taken, rest, queue); // ['a', 'b'] ['c', 'd'] ['a', 'b', 'c', 'd']Code that converts const removed = arr.splice(...) into const removed = arr.toSpliced(...) keeps the same variable name but now holds something completely different. Watch for that during refactors.
with
with(index, value) returns a copy with one element replaced. It is the copying form of index assignment, and it is the cleanest way to update one item when you already know its position:
const todos = [
{ id: 1, text: 'Write', done: false },
{ id: 2, text: 'Review', done: false }
];
const next = todos.with(1, { ...todos[1], done: true });
console.log(todos[1].done); // false
console.log(next[1].done); // true
console.log(next[0] === todos[0]); // true, untouched items are sharedwith behaves differently from bracket assignment in two ways:
- Negative indices count from the end.
arr.with(-1, x)replaces the last element.arr[-1] = xcreates a property named"-1"instead. - An index outside the range
-lengthtolength - 1throws aRangeError. Bracket assignment past the end grows the array and leaves holes.
const letters = ['a', 'b', 'c'];
console.log(letters.with(-1, 'z')); // ['a', 'b', 'z']
try {
letters.with(5, 'x');
} catch (err) {
console.log(err instanceof RangeError); // true
}with cannot append. To add an element at the end, use [...arr, value] or arr.toSpliced(arr.length, 0, value).
Edge Cases and Gotchas
Sparse arrays become dense
A sparse array has holes, meaning indices with no element at all. The copying methods read every index from 0 to length - 1, so holes come out as real undefined values. sort behaves differently: it moves holes to the end and keeps them as holes.
const sparse = [3, , 1];
console.log(sparse.toSorted()); // [1, 3, undefined]
console.log(1 in sparse.with(0, 9)); // true, the hole is now a real undefinedThe result is always a plain Array
If you subclass Array, map and filter return instances of your subclass through Symbol.species. The four copying methods ignore Symbol.species and always return a plain Array. This was a deliberate design choice to keep them simple and predictable.
class Stack extends Array {}
const s = Stack.from([2, 1]);
console.log(s.map(x => x) instanceof Stack); // true
console.log(s.toSorted() instanceof Stack); // falseThey work on frozen arrays
The mutating methods throw a TypeError on a frozen array, even outside strict mode, because built-in methods always report failed writes. The copying methods only read from the source, so they work fine. That makes them a natural fit once you start freezing state, which a later chapter covers.
const frozen = Object.freeze([3, 1, 2]);
console.log(frozen.toSorted()); // [1, 2, 3]
try {
frozen.sort();
} catch (err) {
console.log(err instanceof TypeError); // true
}Typed arrays and array-likes
Typed arrays such as Int32Array get toSorted, toReversed, and with, each returning a new typed array of the same kind. They do not get toSpliced, because a typed array cannot change length. A typed array's toSorted sorts numerically by default, unlike the plain array version.
The methods are also generic, so you can call them on array-like objects:
const arrayLike = { length: 3, 0: 'c', 1: 'a', 2: 'b' };
console.log(Array.prototype.toSorted.call(arrayLike)); // ['a', 'b', 'c']
console.log(new Int32Array([10, 1, 2]).toSorted()); // Int32Array [1, 2, 10]Runtime support
The methods ship in Node.js 20, Chrome and Edge 110, Firefox 115, and Safari 16. If you target older runtimes, use a polyfill such as core-js, or fall back to copy-then-mutate:
| Copying method | Pre-ES2023 equivalent |
|---|---|
| `arr.toSorted(fn)` | `[...arr].sort(fn)` |
| `arr.toReversed()` | `[...arr].reverse()` |
| `arr.toSpliced(i, n, ...items)` | `[...arr.slice(0, i), ...items, ...arr.slice(i + n)]` for non-negative `i` |
| `arr.with(i, v)` | `arr.map((x, j) => (j === i ? v : x))` for in-range `i` |
The fallbacks do not handle every edge case the same way. For example, the map version of with never throws for a bad index, and spread copies holes as undefined while slice keeps them.
Performance Notes
Each call allocates a new array of length n and copies every reference, so each one costs O(n) time and memory on top of the work itself. toSorted is O(n log n) for the sort plus O(n) for the copy, which is the same cost as [...arr].sort(). In practice the copy rarely matters for arrays of a few thousand items. Chaining several copying calls in a hot loop creates one temporary array per call. In that case, copy once and then mutate the private copy, which is safe because no other code holds a reference to it:
const data = [5, 3, 8, 1];
// Three allocations:
const a = data.toSorted((x, y) => x - y).toReversed().with(0, 0);
// One allocation; the copy is local, so mutating it is safe:
const b = [...data].sort((x, y) => x - y).reverse();
b[0] = 0;
console.log(a, b); // [0, 5, 3, 1] [0, 5, 3, 1]Exercises
Exercise
Given const prices = [20, 5, 100];, what does prices.toSorted() return, and how do you get ascending numeric order?
Show answer
It returns [100, 20, 5], because the default comparison converts numbers to strings and "100" < "20" < "5" in string order. Use prices.toSorted((a, b) => a - b) to get [5, 20, 100]. In both cases prices is unchanged.
Exercise
A teammate refactors const removed = list.splice(2, 1); to const removed = list.toSpliced(2, 1);. What bug did they introduce, and how should it be written?
Show answer
toSpliced returns the new array without the item, not the removed item, so removed now holds the remaining list. Read the removed item with const removed = list.slice(2, 3); and build the new list with const next = list.toSpliced(2, 1);.
Exercise
What does this code log, and why? const ids = ['a', 'b', 'c']; const i = ids.findIndex(x => x === 'z'); console.log(ids.with(i, 'z'));
Show answer
It logs ['a', 'b', 'z']. findIndex returns -1 when nothing matches, and with treats -1 as the last index, so it replaces 'c'. Check if (i !== -1) before calling with.
Exercise
Write an expression that returns a copy of const tasks = [{ id: 1, done: false }, { id: 2, done: false }]; with the second task marked done, reusing the first task object, without using map.
Show answer
tasks.with(1, { ...tasks[1], done: true }). The result is a new array whose index 0 is the same object as tasks[0] and whose index 1 is a new object. tasks itself and tasks[1] are unchanged.