toSorted, toReversed and with() in JavaScript
Intermediate · 3 min read
Four of the most used array methods, sort, reverse, splice and setting an item with xs[i] = value, all change the array you call them on. That is fine until another part of your program is holding the same array and gets a surprise. For years the fix was to copy first: [...xs].sort(). Now JavaScript has copying versions built in.
In this tutorial you will use toSorted, toReversed, toSpliced and with, and prove each time that the original array survived. You will also write a fallback for older browsers that don't have them yet. You should know arrays, spread (...) and what sort and splice do.
Mutating and copying
A method mutates an array when it changes that array. A copying method leaves the original alone and returns a new array with the change made.
const nums = [3, 1, 2];
const sorted = nums.sort((a, b) => a - b);
console.log(nums); // [ 1, 2, 3 ]: the original changed
console.log(sorted === nums); // true: same array, two names
The new methods are the copying twins of the old ones:
toSortedissortwithout the mutation;toReversedisreversewithout the mutation;toSplicedissplicewithout the mutation;with(i, value)isxs[i] = valuewithout the mutation.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
29 The copying methods
fairtoSorted, toReversed, toSpliced and with are the non-mutating twins of sort, reverse, splice and index assignment. Use each one and prove the input survived.
Stuck? Three hints, smallest first
- 1. They are recent additions, so feature-test rather than assume:
typeof Array.prototype.toSorted === ‘function’. - 2. Each returns a new array; the original is untouched in every case.
- 3.
toSorted()with no comparator still sorts as strings, exactly likesort().
Step 1: check the methods exist
These methods were added in 2023, so an older browser may not have them. Test before you use them. Methods shared by every array live on Array.prototype.
const hasCopying = ['toSorted', 'toReversed', 'toSpliced', 'with']
.every((m) => typeof Array.prototype[m] === 'function');
console.log(typeof hasCopying); // boolean
every is true only if all four names are functions. This check is called feature testing: you ask the engine what it supports instead of guessing.
Step 2: toSorted and toReversed
const nums = [3, 1, 2];
console.log(nums.toSorted((a, b) => a - b)); // [ 1, 2, 3 ]
console.log(nums.toReversed()); // [ 2, 1, 3 ]
console.log(nums); // [ 3, 1, 2 ]
Each call returns a new array, and nums keeps its order. toReversed reverses [3, 1, 2], the original, because the sort before it changed nothing.
Step 3: toSpliced and with
toSpliced(start, count) removes count items starting at start. with(i, value) replaces the item at index i.
const nums = [3, 1, 2];
console.log([1, 2, 3, 4].toSpliced(1, 2)); // [ 1, 4 ]
console.log(nums.with(0, 'x')); // [ 'x', 1, 2 ]
console.log(nums); // [ 3, 1, 2 ]
toSpliced(1, 2) dropped the items at indexes 1 and 2. Like splice, it can also insert: extra arguments are added at start.
Step 4: a fallback for older engines
Write one small wrapper per method. Each uses the built-in when it exists and the older copy-first idiom when it doesn't.
const hasCopying = ['toSorted', 'toReversed', 'toSpliced', 'with']
.every((m) => typeof Array.prototype[m] === 'function');
const sortedCopy = (xs, cmp) => (hasCopying ? xs.toSorted(cmp) : [...xs].sort(cmp));
const reversedCopy = (xs) => (hasCopying ? xs.toReversed() : [...xs].reverse());
const splicedCopy = (xs, start, count) =>
hasCopying ? xs.toSpliced(start, count) : [...xs.slice(0, start), ...xs.slice(start + count)];
const withCopy = (xs, i, v) =>
hasCopying ? xs.with(i, v) : xs.map((old, k) => (k === i ? v : old));
const nums = [3, 1, 2];
console.log(sortedCopy(nums, (a, b) => a - b)); // [ 1, 2, 3 ]
console.log(reversedCopy(nums)); // [ 2, 1, 3 ]
console.log(splicedCopy([1, 2, 3, 4], 1, 2)); // [ 1, 4 ]
console.log(withCopy(nums, 0, 'x')); // [ 'x', 1, 2 ]
console.log(nums); // [ 3, 1, 2 ]
Look at the fallbacks, because they show what each new method replaces. Spread then sort. Spread then reverse. Two slices joined together, skipping the removed part. A map that swaps in the new value at one index. The results are the same either way.
Step 5: two things that didn't change
const nums = [3, 1, 2];
console.log(nums.toSorted() === nums); // false
console.log([10, 9, 1].toSorted()); // [ 1, 10, 9 ]
const records = [{ id: 2 }, { id: 1 }];
console.log(records.toSorted((a, b) => a.id - b.id)[1] === records[0]); // true
The first line confirms you always get a different array. The second is a trap carried over from sort: with no compare function, toSorted still compares as text, so 10 lands before 9. The third shows that the copy is shallow: it is a new array, but it holds the same objects as the original. Change one of those objects and both arrays see the change.
The full solution
The panel feature-tests the four methods, wraps each one with its fallback, and prints the original after every call. Press Run and check the first line, which tells you whether your browser has the methods.
const hasCopying = ['toSorted', 'toReversed', 'toSpliced', 'with']
.every((m) => typeof Array.prototype[m] === 'function');
// Each wrapper uses the built-in where it exists and the old idiom otherwise,
// so the checks below are honest on any engine.
const sortedCopy = (xs, cmp) => (hasCopying ? xs.toSorted(cmp) : [...xs].sort(cmp));
const reversedCopy = (xs) => (hasCopying ? xs.toReversed() : [...xs].reverse());
const splicedCopy = (xs, start, count) =>
hasCopying ? xs.toSpliced(start, count) : [...xs.slice(0, start), ...xs.slice(start + count)];
const withCopy = (xs, i, v) =>
hasCopying ? xs.with(i, v) : xs.map((old, k) => (k === i ? v : old));
const nums = [3, 1, 2];
console.log('this engine has the copying methods:', hasCopying);
console.log('toSorted :', sortedCopy(nums, (a, b) => a - b), ' original:', nums);
console.log('toReversed :', reversedCopy(nums), ' original:', nums);
console.log('toSpliced :', splicedCopy([1, 2, 3, 4], 1, 2), '<- removed indexes 1 and 2');
console.log('with :', withCopy(nums, 0, 'x'), ' original:', nums);
console.log('no comparator still means string order:', sortedCopy([10, 9, 1]));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('toSorted returns a sorted copy', sortedCopy(nums, (a, b) => a - b), [1, 2, 3]);
test('and the original keeps its order', nums, [3, 1, 2]);
test('toReversed copies as well', reversedCopy(nums), [2, 1, 3]);
test('toSpliced removes without mutating', splicedCopy([1, 2, 3, 4], 1, 2), [1, 4]);
test('with replaces one index', withCopy(nums, 0, 'x'), ['x', 1, 2]);
test('every one of them returns a different array', sortedCopy(nums, (a, b) => a - b) === nums, false);
test('toSorted with no comparator still sorts as text', sortedCopy([10, 9, 1]), [1, 10, 9]);
test('the feature test answered with a boolean', typeof hasCopying, 'boolean');
test('and the mutating versions are still there when you want them', (() => { const a = [2, 1]; a.sort(); return a; })(), [1, 2]);
These four close a long-standing gap: before them, "sort without mutating" meant remembering to spread first, and forgetting was a bug that only showed up in whatever code held the other reference. xs.toSorted(cmp) says what it does.
The wrappers are not decoration. These methods shipped in 2023, so a reader on an older browser would see failures for something that is not their mistake — the feature test keeps the page honest and shows the pre-2023 idiom next to each one. Note that they are still shallow: toSorted gives a new array holding the same objects.
Common mistakes
- Calling
toSorted()on numbers with no compare function. It sorts as text, exactly likesort(). Pass(a, b) => a - b. - Expecting deep copies. The new array holds the same objects. Copy the objects too if you plan to change them.
- Using the methods without a fallback on a public site. Visitors on older browsers get a
TypeError. Feature-test, or copy first with spread.
Try it yourself
- Use
withto change the second item of['tea', 'milk', 'sugar']to'honey', and print both arrays. - Use
toSplicedto insert'bread'at index 1 without removing anything. - Write
sortedBy(xs, key)that returns a copy of a list of objects sorted by one property.