Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Move Item

Immutable Arraysmedium

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

Implement `moveItem(list, from, to)` returning a new array with the element at `from` moved to index `to` (useful for drag-and-drop lists).

Sample tests

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

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Calling splice directly on the state array mutates it.
  • Inserting before removing, which shifts the indices and moves the wrong element.

Learning resources

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

Work on a copy made with [...list]. splice(from, 1) removes and returns the moved element; splice(to, 0, moved) inserts it at the destination. Because all of this happens on the copy, the original array is never touched.

Loading...
⌘/Ctrl + Enter

Run your code to see results.