Skip to content
Exercise · Arrays · lesson 13 of 13

Exercise: insert into an array

Write a function function insertAt(nums, index, ...values) that returns a new array: the elements of nums, with all the values placed before the element at the index index, in the order they were passed. The function does not change the array nums itself, and the result is always a new array, even when there is nothing to insert.

  • insertAt([1, 4], 1, 2, 3) → [1, 2, 3, 4]
  • insertAt([5, 6], 0, 4) → [4, 5, 6]
  • insertAt([1, 2], 2, 3) → [1, 2, 3]

Constraints: nums holds from 0 to 1000 integers; index is an integer from 0 to nums.length inclusive, and when index equals nums.length, the values go at the end; there may be from 0 to 10 values after index.

The tests print the result through JSON.stringify: it turns an array into a string without spaces, for example [1, 2, 3, 4] into [1,2,3,4].

Do not add extra imports unless the task says so explicitly.

insertat.js — javascript
javascript · 4 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way