Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Array State Reducer

Immutable Arraysmedium

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

Implement `arrayReducer(state, action)` for list state: - `{ type: 'add', value }` appends. - `{ type: 'removeAt', index }` removes by index. - `{ type: 'updateAt', index, value }` replaces by index. - `{ type: 'move', from, to }` moves an element. All immutable.

Examples

Input: add 1, add 2, add 3, updateAt(1,9), move(0,2), removeAt(0)
Output: [3, 1]
Becomes [1,9,3] then [9,3,1] after the move, then [3,1] after removing index 0.

Sample tests

Input: sequence of array ops
Output: [3,1]
Input: removeAt
Output: [1,3]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Calling splice on the state array directly mutates it.

Learning resources

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

A reducer over array actions centralizes immutable list updates, the pattern behind useReducer-managed lists.

Loading...
⌘/Ctrl + Enter

Run your code to see results.