Insert or remove array items immutably in JavaScript
Beginner · 3 min read
In a lot of modern code you are not allowed to change an array in place. React state, Redux reducers and many other tools decide whether something changed by checking if it is a different array. If you splice the old one, it is still the same array, and the screen may not update. So you need ways to insert, remove and replace items that build a new array and leave the input alone. Working this way is called immutable updating.
In this tutorial you will write three small functions: insertAt, removeAt and replaceAt. Each one is a single line. You should know slice, arrow functions and arrays. The spread syntax and rest parameters are explained below.
Spread inside an array
Three dots inside square brackets spread an array out, as if you had typed its items one by one. That makes it easy to glue pieces together into a new array.
const left = [1, 2];
const right = [4, 5];
console.log([...left, 3, ...right]); // [ 1, 2, 3, 4, 5 ]
slice, the key tool
slice(start, end) copies a range without changing the original. With one argument it copies from start to the end. It also never complains about out-of-range indexes. It just clamps them to fit:
const xs = [1, 2];
console.log(xs.slice(0, 99)); // [ 1, 2 ]
console.log(xs.slice(99)); // []
That forgiving behavior will handle the edge cases for us.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
16 Insert, remove and replace without mutating
easyWrite insertAt, removeAt and replaceAt that all return a new array and leave the input alone.
Stuck? Three hints, smallest first
- 1. Two slices and a spread: everything before the index, the new values, everything after.
- 2.
sliceclamps out-of-range indexes rather than throwing, which handles the edges for free. - 3.
replaceAtis just amapthat changes one position.
Step 1: the plan for insertAt
To insert at index i, take everything before i, then the new value, then everything from i onwards.
const xs = ['Yaba', 'Mushin', 'Oshodi'];
const before = xs.slice(0, 1);
const after = xs.slice(1);
console.log([...before, 'Surulere', ...after]); // [ 'Yaba', 'Surulere', 'Mushin', 'Oshodi' ]
Step 2: insertAt, with any number of values
Now wrap that in a function. ...values in the parameter list is a rest parameter: it collects every argument after i into an array, so you can insert one value or several.
const insertAt = (xs, i, ...values) => [...xs.slice(0, i), ...values, ...xs.slice(i)];
const stops = ['Yaba', 'Mushin', 'Oshodi'];
console.log(insertAt(stops, 1, 'Surulere')); // [ 'Yaba', 'Surulere', 'Mushin', 'Oshodi' ]
console.log(insertAt([3, 4], 0, 1, 2)); // [ 1, 2, 3, 4 ]
console.log(insertAt([1, 2], 99, 'x')); // [ 1, 2, 'x' ]
console.log(stops); // [ 'Yaba', 'Mushin', 'Oshodi' ]
The same three dots do two jobs: in the parameters they collect, in the array they spread. An index past the end appends, with no special case, because slice clamps 99 down to the length. And stops is untouched.
Step 3: removeAt
To remove, keep everything before i and everything after the removed part. With a count, the part after starts at i + count.
const removeAt = (xs, i, count = 1) => [...xs.slice(0, i), ...xs.slice(i + count)];
console.log(removeAt([1, 2, 3], 1)); // [ 1, 3 ]
console.log(removeAt([1, 2, 3, 4], 1, 2)); // [ 1, 4 ]
console.log(removeAt([1, 2], 99)); // [ 1, 2 ]
count = 1 is a default parameter, so a plain call removes one item. Removing an index that isn't there gives back an unchanged copy, again thanks to slice clamping.
Step 4: replaceAt
Replacing one item doesn't change the length, so map fits perfectly. Its callback gets each item v and its index k. Return the new value at position i, and the old one everywhere else.
const replaceAt = (xs, i, value) => xs.map((v, k) => (k === i ? value : v));
const stops = ['Yaba', 'Mushin', 'Oshodi'];
console.log(replaceAt(stops, 0, 'Ebute Metta')); // [ 'Ebute Metta', 'Mushin', 'Oshodi' ]
console.log(stops); // [ 'Yaba', 'Mushin', 'Oshodi' ]
condition ? a : b gives a when the condition is true, otherwise b.
Step 5: why not just splice?
splice is shorter, but it changes the array you already have:
const state = [1, 2, 3];
const before = state;
state.splice(1, 1);
console.log(state === before); // true: still the same array
const next = [...state.slice(0, 1), ...state.slice(2)];
console.log(next === before); // false: a new array
A tool that checks "is this a different array?" would think nothing happened after the splice. The copying versions always produce a new array, so the change is easy to spot.
Step 6: the built-in with()
Newer JavaScript engines have with(i, value), a copying replace built into arrays.
console.log([1, 2, 3].with(1, 'x')); // [ 1, 'x', 3 ]
It is recent, so the answer panel checks it exists before using it. Your replaceAt works everywhere.
The full solution
The panel defines all three functions, uses them on a list of stops, and shows the original afterwards, unchanged. Press Run to see the output.
const insertAt = (xs, i, ...values) => [...xs.slice(0, i), ...values, ...xs.slice(i)];
const removeAt = (xs, i, count = 1) => [...xs.slice(0, i), ...xs.slice(i + count)];
const replaceAt = (xs, i, value) => xs.map((v, k) => (k === i ? value : v));
const stops = ['Yaba', 'Mushin', 'Oshodi'];
// The built-in copying replace, where the engine has it.
const hasWith = typeof Array.prototype.with === 'function';
const builtIn = hasWith ? [1, 2, 3].with(1, 'x') : [1, 'x', 3];
console.log('insert :', insertAt(stops, 1, 'Surulere'));
console.log('remove :', removeAt(stops, 1));
console.log('replace :', replaceAt(stops, 0, 'Ebute Metta'));
console.log('original:', stops, '<- untouched by all three');
console.log('insert past the end appends:', insertAt(stops, 99, 'Ikeja'));
console.log('with() available here?', hasWith, '->', builtIn);
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('insert in the middle', insertAt([1, 2, 3], 1, 'x'), [1, 'x', 2, 3]);
test('insert several at once, at the start', insertAt([3, 4], 0, 1, 2), [1, 2, 3, 4]);
test('an index past the end appends', insertAt([1, 2], 99, 'x'), [1, 2, 'x']);
test('remove one element', removeAt([1, 2, 3], 1), [1, 3]);
test('remove two', removeAt([1, 2, 3, 4], 1, 2), [1, 4]);
test('removing an index that is not there changes nothing', removeAt([1, 2], 99), [1, 2]);
test('replace one element', replaceAt([1, 2, 3], 1, 'x'), [1, 'x', 3]);
test('the input array is never modified', stops, ['Yaba', 'Mushin', 'Oshodi']);
test('with() does the same job where the engine has it', builtIn, [1, 'x', 3]);
These three are worth memorising because they are what you need in any code that treats state as immutable — a reducer, a signal, anything that compares by reference to decide whether to re-render. splice would be shorter and would break that comparison, since the array object stays the same.
slice doing the clamping is what keeps them short: slice(0, 99) on a two-element array gives both elements rather than complaining, so insertAt(xs, 99, v) appends and removeAt(xs, 99) is a no-op with no special cases written.
with(i, value) is the built-in copying replace. It is recent, so the assertion feature-tests it rather than assuming — the fallback keeps the check honest on an older engine.
Common mistakes
- Using
splicein code that needs a new array. The array stays the same object, so change checks miss it. - Forgetting the spread.
[xs.slice(0, i), value, xs.slice(i)]gives an array of arrays. Each slice needs...in front. - Removing with
slice(i)instead ofslice(i + count). That keeps the item you meant to remove.
Try it yourself
- Write
moveItem(xs, from, to)usingremoveAtandinsertAt. - Use
insertAtto add0at the start of[1, 2, 3], and99at the end. - Write
updateWhere(xs, pred, value)that replaces every item matchingpred, usingmap.