Update One Array Item Without Mutating
map plus spread replaces the one matching record and keeps every other element at its original reference, so unchanged items stay referentially identical.
Code
const tasks = [
{ id: 't1', done: false, title: 'write spec' },
{ id: 't2', done: false, title: 'review pr' },
{ id: 't3', done: false, title: 'ship' },
];
function completeTask(tasks, id) {
return tasks.map((task) => (task.id === id ? { ...task, done: true } : task));
}
const next = completeTask(tasks, 't2');
console.log(next.map((t) => t.id + ':' + t.done).join(' | '));
console.log('original untouched:', tasks.map((t) => t.done).join(','));
// non-matching elements keep their original references: only t2 is a new object
console.log('t1 same ref:', next[0] === tasks[0], '| t2 new ref:', next[1] !== tasks[1]);
// contrast: writing tasks[1].title directly mutates the shared array in place, and every holder sees the new value at once;
// next[1] is the copy made earlier and still carries the old title
tasks[1].title = 'renamed in place';
console.log('mutated in place:', tasks[1].title, '| copy keeps:', next[1].title);What the code does
Update One Array Item Without Mutating reduces to the function completeTask.
Applying it
The primary signature is function completeTask(tasks, id)
The demo output is labeled (original untouched:, t1 same ref:, mutated in place:), so every printed line maps back to its originating operation.
Statements that matter
return tasks.map((task) => (task.id === id ? { ...task, done: true } : task));
Interactive Tools for This Topic
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `completeTask` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.