JavaScript Snippet

Insert, Update, Remove Items by Index

Difficulty: Easy

Index-based mutations are where most array bugs come from: `splice` mutates in place and is easy to misuse, while `slice` plus spread gives you a copy without mutating the input. This snippet contrasts the mutable and immutable forms for the four common index operations (remove by index, update by index, insert at index, remove all matching a predicate). Keep mutation explicit at the call site so reviewers know whether the original array survives.

Code Snippets
/

Insert, Update, Remove Items by Index

Insert, Update, Remove Items by Index

Index-based mutations are where most array bugs come from: `splice` mutates in place and is easy to misuse, while `slice` plus spread gives you a copy without mutating the input. This snippet contrasts the mutable and immutable forms for the four common index operations (remove by index, update by index, insert at index, remove all matching a predicate). Keep mutation explicit at the call site so reviewers know whether the original array survives.

JavaScript
Easy
4 snippets
arrays
array-manipulation-patterns
js-spread-rest

332 views

8

splice(i, 1) removes one item starting at index i and mutates the array, which is fast but surprising in shared state. The immutable form copies the prefix and suffix around the removed index using slice and the spread operator, so callers can rely on the original array surviving. Pick the mutable form only when you own the array and the mutation is the explicit intent (a queue you are draining, for example). For React state, props, or any data passed across module boundaries, default to the immutable variant so equality checks like prev !== next keep working.