Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Insert at Index

Immutable Arraysmedium

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

Implement `insertAt(list, index, item)` returning a new array with `item` inserted at `index`.

Sample tests

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

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • splice inserts in place and mutates the original array.
  • Forgetting that an index beyond the length just appends the item.

Learning resources

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

slice(0, index) is everything before the insertion point and slice(index) is everything after. Spreading them around the new item produces a fresh array with the item inserted, leaving the original alone.

Loading...
⌘/Ctrl + Enter

Run your code to see results.