Back to Freecodecamp

Challenge 212: Array Insertion

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6994cff2290543b3aec9f511.md

latest1.1 KB
Original Source

--description--

Given an array, a value to insert into the array, and an index to insert the value at, return a new array with the value inserted at the specified index.

--hints--

insertIntoArray([2, 4, 8, 10], 6, 2) should return [2, 4, 6, 8, 10].

js
assert.deepEqual(insertIntoArray([2, 4, 8, 10], 6, 2), [2, 4, 6, 8, 10]);

insertIntoArray(["the", "quick", "fox"], "brown", 2) should return ["the", "quick", "brown", "fox"].

js
assert.deepEqual(insertIntoArray(["the", "quick", "fox"], "brown", 2), ["the", "quick", "brown", "fox"]);

insertIntoArray([], 0, 0) should return [0].

js
assert.deepEqual(insertIntoArray([], 0, 0), [0]);

insertIntoArray([0, 1, 1, 2, 3, 8, 13], 5, 5) should return [0, 1, 1, 2, 3, 5, 8, 13].

js
assert.deepEqual(insertIntoArray([0, 1, 1, 2, 3, 8, 13], 5, 5), [0, 1, 1, 2, 3, 5, 8, 13]);

--seed--

--seed-contents--

js
function insertIntoArray(arr, value, index) {

  return arr;
}

--solutions--

js
function insertIntoArray(arr, value, index) {
  return [
    ...arr.slice(0, index),
    value,
    ...arr.slice(index)
  ];
}