Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Update by Index

Immutable Arrayseasy

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

Implement `updateAt(list, index, value)` returning a new array with the element at `index` replaced by `value`.

Sample tests

Input: updateAt([1,2,3], 1, 9)
Output: [1,9,3]
Input: updateAt([5], 0, 7)
Output: [7]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • list[index] = value mutates the original array.
  • When elements are objects, returning value replaces the whole object; spread it if you only mean to change one field.

Learning resources

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

map returns a new array. At the matching index you return value; at every other position you return the original element, so only one slot changes while the rest are preserved.

Loading...
⌘/Ctrl + Enter

Run your code to see results.