Sub topic 6
toSorted, toReversed, toSpliced, and with
This chapter assumes you know how array references work and how map, filter, and spread build new arrays from the previous chapter. It covers four methods added in ES2023 that fill a gap those tools leave open.
The gap these methods fill
map and filter never touch the original array. Four common operations still do: sort, reverse, splice, and assignment by index (arr[i] = x). To use them safely you had to copy first:
const scores = [42, 7, 19];
const sortedOld = [...scores].sort((a, b) => a - b);
console.log(scores); // [42, 7, 19]
console.log(sortedOld); // [7, 19, 42]The pattern works, but you can forget the [...scores] step. Then sort changes the shared array in place, with no error to warn you. ES2023 added a copying counterpart for each of these operations, so the safe version takes no extra step.
| Mutating | Copying (ES2023) | Returns |
|---|---|---|
| `sort(fn)` | `toSorted(fn)` | New sorted array |
| `reverse()` | `toReversed()` | New reversed array |
| `splice(start, count, ...items)` | `toSpliced(start, count, ...items)` | New array with the edit applied |
| `arr[i] = value` | `with(i, value)` | New array with one slot replaced |
The methods in action
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 untouchedEvery call reads nums and returns a fresh array. Note that toSpliced returns the resulting array, whereas splice returns the removed elements. If you move code from splice to toSpliced without accounting for that, you introduce a bug.
Details that cause surprises
- The default sort compares strings.
toSorteduses the same comparison assort.[10, 9, 1].toSorted()gives[1, 10, 9]. Pass(a, b) => a - bfor numbers. withchecks bounds.[1, 2].with(5, 0)throws aRangeError. It does not grow the array the wayarr[5] = 0does. Negative indexes count from the end:[1, 2, 3].with(-1, 0)gives[1, 2, 0].- The copies are shallow. The new array holds the same object references as the original.
todos.toSorted(byTitle)[0].done = truestill changes an object that the old array shares. - Holes become
undefined. On sparse arrays, these methods fill empty slots withundefinedand never return a sparse array. - Typed arrays get three of them.
Int8Arrayand its relatives havetoSorted,toReversed, andwith. They do not havetoSpliced.
Using them in state updates
These methods return new arrays, so they work well where a state update needs a new reference:
const state = { items: ['b', 'c', 'a'] };
const next = { ...state, items: state.items.toSorted() };
console.log(state.items); // ['b', 'c', 'a']
console.log(next.items); // ['a', 'b', 'c']
console.log(next.items === state.items); // falseExercise
Given const list = ['x', 'y', 'z'], write one expression that returns a new array with 'y' replaced by 'Y' and 'z' removed, leaving list unchanged. What does list.with(3, 'w') do?
Show answer
list.with(1, 'Y').toSpliced(2, 1) returns ['x', 'Y'] and leaves list as ['x', 'y', 'z']. list.with(3, 'w') throws a RangeError, because index 3 is out of bounds and with never extends an array.
Exercise
A teammate replaces const removed = arr.splice(2, 1) with const removed = arr.toSpliced(2, 1). What changes about the value of removed?
Show answer
splice returns the removed elements, so removed was a one-element array holding the old arr[2]. toSpliced returns the whole new array without that element, so removed now holds the remaining items. To get the removed item without mutating arr, read arr[2] or use arr.slice(2, 3).