Slice and Splice - index n problem

Slice and Splice - index n problem
0

#1

Tell us what’s happening:

Hi
Please: what am I doing wrong here? The contents of arr1 are being added to the end of arr2, and not at index n, not sure why.

Your code so far


function frankenSplice(arr1, arr2, n) {
  let arr2Copy = []
  arr2Copy.push(arr2)
  arr2Copy.splice(n, 0, arr1.slice())
  return arr2Copy;
}

frankenSplice([1, 2, 3], [4, 5, 6], 1);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/slice-and-splice


#2

You have a couple of issues.

#1) You do not need to make a copy of arr1 (with the slice), but you do need to make a copy of arr2 (you can use slice for that).

#2) Use my slice suggestion for the arr2Copy, because what you are doing right now is pushing arr2 into another array, so instead of arr2Copy looking like:

[ 4, 5, 6 ]

it instead looks like:

[ [ 4, 5, 6 ] ]

#3) After the first and second arguments, the splice methods accepts a list of arguments which are values which will be spliced into the array at the index designated by the first argument. You are trying to pass an array instead of a list of arguments. You could use the spread operator to spread the array into a list of arguments.


#3

Thanks for this info Randell, that makes total sense and I now understand :slight_smile:
thanks again for coming to my rescue!