Sub topic 5
Transforming Arrays Without Mutation
This chapter assumes you know how references work for arrays and objects, and that you can copy an object with spread syntax. Here you will learn the standard patterns for adding, removing, and updating array items while leaving the original array unchanged.
Mutating and non-mutating methods
Some array methods change the array they are called on. Others return a new array and leave the original alone. Mixing the two up is the most common source of accidental mutation.
| Mutates the original | Returns a new array |
|---|---|
| `push`, `pop`, `shift`, `unshift` | `concat`, spread `[...arr]` |
| `splice` | `slice` |
| `sort`, `reverse` | `map`, `filter` |
| `fill`, `copyWithin`, `arr[i] = x` | `flatMap`, `flat` |
sort and reverse catch many developers out. Both return the array, which makes them look non-mutating, but the array they return is the original one after it has been reordered.
The three core patterns
Most immutable array work comes down to adding, removing, or updating items. Each of these has a standard one-line form.
const todos = [
{ id: 1, text: 'Write', done: false },
{ id: 2, text: 'Review', done: false }
];
const added = [...todos, { id: 3, text: 'Ship', done: false }];
const removed = todos.filter(t => t.id !== 1);
const toggled = todos.map(t => (t.id === 2 ? { ...t, done: !t.done } : t));
console.log(todos.length); // 2, the original array is unchanged
console.log(toggled[0] === todos[0]); // true, unchanged items are reusedIn the map call, only the item that changes gets a new object, built with { ...t, done: !t.done }. Every other item is returned as it is. Reusing the unchanged items is cheap, and it lets later code tell which items changed by comparing references.
Inserting and removing by position
To work with a position instead of an id, use slice to cut the array into pieces and spread the pieces back together.
const letters = ['a', 'b', 'd'];
const i = 2;
const inserted = [...letters.slice(0, i), 'c', ...letters.slice(i)];
const withoutIndex1 = [...letters.slice(0, 1), ...letters.slice(2)];
const prepended = ['z', ...letters];
console.log(inserted); // ['a', 'b', 'c', 'd']
console.log(withoutIndex1); // ['a', 'd']
console.log(prepended); // ['z', 'a', 'b', 'd']
console.log(letters); // ['a', 'b', 'd']To sort without mutating, copy the array first: [...nums].sort((a, b) => a - b). The next chapter covers newer built-in methods that do this in one step.
Common errors
These mistakes come up often in code review:
- Mutating inside
map. Writingtodos.map(t => { t.done = true; return t; })gives you a new array that holds the same objects, and every one of those objects has been changed. Return a copy instead:{ ...t, done: true }. - Building with
forEachandpushon the source. Pushing to a fresh local array is fine. Pushing to the input array mutates it. - Forgetting the return in a block body.
arr.map(x => { x * 2 })returnsundefinedfor every element. Either writereturninside the braces or drop the braces. - Assuming
sliceandsplicebehave alike.slicecopies a section of the array.spliceremoves items from the original in place.
Exercise
Given const items = [{ id: 1, qty: 1 }, { id: 2, qty: 5 }], write one expression that returns a new array where the item with id 2 has qty 6, without mutating items or any object inside it.
Show answer
items.map(it => (it.id === 2 ? { ...it, qty: it.qty + 1 } : it)). The item with id 2 is replaced by a new object, and the item with id 1 is reused unchanged.
Exercise
Why does const sorted = scores.sort((a, b) => a - b) break immutability even though it assigns the result to a new variable?
Show answer
sort reorders scores in place and returns that same array, so sorted === scores is true. Copy first with [...scores].sort((a, b) => a - b).