Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Move Item in a List

Immutable Arraysmedium

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

Drag-to-reorder UIs need to move an item to a new position without mutating state. Implement `moveItem(list, from, to)` returning a new array with the element at index `from` moved to index `to`.

Sample tests

Input: moveItem([1,2,3,4], 0, 2)
Output: [2,3,1,4]
Input: moveItem(["a","b","c"], 2, 0)
Output: ["c","a","b"]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Calling splice on the original array mutates state, so React may not re-render.
  • Inserting before removing shifts the indices and moves the wrong element.

Learning resources

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

Spreading into a fresh array keeps the original untouched. splice(from, 1) extracts the item, and splice(to, 0, item) re-inserts it at the destination. Returning the copy gives React a new reference.

Loading...
⌘/Ctrl + Enter

Run your code to see results.