Sub topic 5
Transforming Arrays Without Mutation
This chapter assumes you know how JavaScript arrays and arrow functions work. It also assumes you have read the earlier chapters on reference semantics and spread copies. Arrays are objects, so every variable that points to an array points to the same array. Any method that changes the array in place is therefore visible through every one of those references. The fix is to use methods that return a new array and leave the original alone.
The Working Model: Mutators vs. Copiers
Every array method falls into one of two groups:
- Mutating methods change the array they are called on. Many also return that same array, which makes the change easy to miss.
- Non-mutating methods read the original and return a new array (or a new value). The original stays the same.
| Intent | Mutating method | Non-mutating alternative |
|---|---|---|
| Add to end | `push` | `[...arr, item]` or `arr.concat(item)` |
| Add to start | `unshift` | `[item, ...arr]` |
| Remove last / first | `pop` / `shift` | `arr.slice(0, -1)` / `arr.slice(1)` |
| Remove by condition | `splice` in a loop | `arr.filter(...)` |
| Update one item | `arr[i] = x` | `arr.map(...)` |
| Insert at index | `splice(i, 0, x)` | `[...arr.slice(0, i), x, ...arr.slice(i)]` |
| Sort | `sort` | `[...arr].sort(...)` |
| Reverse | `reverse` | `[...arr].reverse()` |
| Fill | `fill`, `copyWithin` | `arr.map(() => value)` |
The read-only methods map, filter, slice, concat, reduce, flat, flatMap, find, some, every, includes, and indexOf never change the array they are called on. Your callback can still mutate the array, though. That problem gets its own section below.
The Core Patterns
Add, Remove, Update
Most immutable array work comes down to three operations. Each one returns a new array, and items you didn't touch are reused rather than copied.
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 reusedThe map callback has two branches, and this is the key detail. For the item being changed, it returns a new object built with spread. For every other item, it returns the same object. Code that compares references (covered in a later chapter) can then tell exactly which item changed.
Insert and Remove by Position
slice(start, end) returns a copy of a range without touching the source. Combine it with spread to insert or remove by index:
const letters = ['a', 'b', 'd', 'e'];
function insertAt(arr, index, item) {
return [...arr.slice(0, index), item, ...arr.slice(index)];
}
function removeAt(arr, index) {
return [...arr.slice(0, index), ...arr.slice(index + 1)];
}
console.log(insertAt(letters, 2, 'c')); // ['a', 'b', 'c', 'd', 'e']
console.log(removeAt(letters, 0)); // ['b', 'd', 'e']
console.log(letters); // ['a', 'b', 'd', 'e']slice accepts negative indices, so arr.slice(0, -1) drops the last item and arr.slice(-2) keeps the last two. If you need a one-line remove by index, arr.filter((_, i) => i !== index) also works.
Reorder by Copying First
sort and reverse mutate the array and return the same array. That return value is the trap. Code like const sorted = items.sort() looks like it produces a new array. In fact sorted === items is true, and items has been reordered.
const scores = [40, 100, 1, 5];
const bad = scores.sort((a, b) => a - b);
console.log(bad === scores); // true: scores itself was reordered
const prices = [40, 100, 1, 5];
const good = [...prices].sort((a, b) => a - b);
console.log(good); // [1, 5, 40, 100]
console.log(prices); // [40, 100, 1, 5]The copy-then-sort idiom works in every JavaScript engine. Newer runtimes also have toSorted and toReversed, which do the same thing in one step. They are covered in the next chapter.
Derive Values with reduce
Use reduce when you want one result from an array, such as a total, a lookup object, or a grouping. Treat the accumulator as a value too. Return a new accumulator on each step, or build it locally and never expose it until the end.
const items = [
{ id: 'a', price: 3, category: 'tools' },
{ id: 'b', price: 7, category: 'books' },
{ id: 'c', price: 5, category: 'tools' }
];
const total = items.reduce((sum, item) => sum + item.price, 0);
const byId = items.reduce((acc, item) => ({ ...acc, [item.id]: item }), {});
console.log(total); // 15
console.log(byId.b.price); // 7Chaining
Non-mutating methods return arrays, so you can chain them. Each step leaves its input intact:
const orders = [
{ id: 1, total: 120, status: 'paid' },
{ id: 2, total: 40, status: 'pending' },
{ id: 3, total: 75, status: 'paid' }
];
const paidTotals = orders
.filter(o => o.status === 'paid')
.map(o => o.total)
.sort((a, b) => b - a); // safe: sort acts on the array map just created
console.log(paidTotals); // [120, 75]
console.log(orders[0].id); // 1, order unchangedHere sort is safe because it runs on a temporary array that map created and nobody else references. A mutating method is only a problem when it acts on an array someone else can see.
Common Errors
Mutating Inside the Callback
map and filter return new arrays, but they hand your callback the original items. If the callback changes an item, you have mutated shared state, and wrapping it in map doesn't help:
const users = [{ name: 'Ada', active: false }];
// Wrong: changes the original object, then returns it
const wrong = users.map(u => {
u.active = true;
return u;
});
console.log(users[0].active); // true: the original was mutated
console.log(wrong[0] === users[0]); // true: same object
const people = [{ name: 'Grace', active: false }];
// Right: return a new object
const right = people.map(u => ({ ...u, active: true }));
console.log(people[0].active); // falseTreating the Result as a Deep Copy
filter, slice, concat, and spread produce shallow copies. The new array is a different array, but its elements are the same objects. filtered[0].name = 'x' changes the object that the original array also holds. If you need to change an element, replace it with a new object as map did above.
Using forEach to Build a Result
forEach that pushes into an outer array works, but it hides intent and invites mutation of variables outside the loop. map, filter, or flatMap say what you mean and return the result directly. flatMap combines filtering and mapping in one pass: return [] to drop an item, or [value] to keep a transformed one.
Expecting push to Return the Array
push and unshift return the new length, and pop and shift return the removed element. Code like setItems(items.push(x)) sets the state to a number and mutates items along the way.
Edge Cases
concatflattens one level of array arguments.[1].concat([2, 3])gives[1, 2, 3], but[1].concat([[2]])gives[1, [2]]. To append an array as one element, use[...arr, inner]orarr.concat([inner]).- Sparse arrays.
mapkeeps holes as holes, andfilterandforEachskip them. Spread andArray.fromturn holes intoundefined.[, 1].map(x => x * 2)has length 2 with a hole at index 0, while[...[, 1]]is[undefined, 1]. - Array-like values.
Array.from(arguments)orArray.from(nodeList, fn)gives you a real array you can transform freely without touching the source. - Default sort order. With no comparator,
sortcompares values as strings, so[10, 9, 1]sorts to[1, 10, 9]. Always pass(a, b) => a - bfor numbers, whether or not you copy first.
Cost
Each non-mutating step allocates a new array of size n, so a chain of three methods creates three arrays. Modern engines handle short-lived arrays well, and for typical UI state the cost can't be measured. The cost does show up in tight loops over very large arrays, or when you rebuild an array once per item, as in the reduce example. In those cases, keep the mutation local to a freshly created array and only expose the finished result. The trade-offs chapter covers this in more depth.
Exercise
Write a function moveItem(arr, from, to) that returns a new array with the element at index from moved to index to, without mutating arr. Test it with moveItem(['a', 'b', 'c', 'd'], 0, 2).
Show answer
Remove the item first, then insert it into the result: function moveItem(arr, from, to) { const item = arr[from]; const without = arr.filter((_, i) => i !== from); return [...without.slice(0, to), item, ...without.slice(to)]; }. The call returns ['b', 'c', 'a', 'd'] and the input array is unchanged.
Exercise
A teammate writes const ranked = players.sort((a, b) => b.score - a.score); return ranked.map(p => { p.rank = ranked.indexOf(p) + 1; return p; });. List the mutations and rewrite it so players and its objects stay unchanged.
Show answer
There are two mutations. sort reorders players in place, and the map callback adds rank to each original object. Rewrite: return [...players].sort((a, b) => b.score - a.score).map((p, i) => ({ ...p, rank: i + 1 }));. Using the index argument also removes the O(n²) indexOf lookup.
Exercise
Why is [1, 2].concat([3], [[4]]) equal to [1, 2, 3, [4]] rather than [1, 2, 3, 4]?
Show answer
concat spreads each array argument by exactly one level. [3] contributes 3, and [[4]] contributes its single element, which is the array [4]. Nested arrays are not flattened further.