Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Update by Id

Immutable Arraysmedium

Course · Section 9: Data Structures, Modern Operators and Strings · Lecture 111: The Spread Operator (...)

Implement `updateById(list, id, patch)` returning a new array where the item with matching `id` is merged with `patch` (other items unchanged).

Sample tests

Input: updateById([{"id":1,"done":false},{"id":2,"done":false}], 1, {"done":true})
Output: [{"id":1,"done":true},{"id":2,"done":false}]
Input: updateById([{"id":1,"n":0}], 1, {"n":5})
Output: [{"id":1,"n":5}]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Mutating the matched item (item.done = true) instead of building a new object.
  • Replacing the whole item with patch and losing fields that were not part of the patch.

Learning resources

  • React: Updating Arrays in State
Approach & explanation (try first)

For the matching id you return a new object { ...item, ...patch }, preserving untouched fields and overriding changed ones. Every other item is returned as-is, so only one row changes identity and the list stays immutable.

Loading...
⌘/Ctrl + Enter

Run your code to see results.