Slice and Splice -I think i code is right, but it does not work

Tell us what’s happening:

Your code so far


function frankenSplice(arr1, arr2, n) {
  // It's alive. It's alive!
  let newarr2 = arr2.slice();
  return newarr2.splice(n,0, ...arr1);

}

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.

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

.splice() returns an array of the elements that have been removed out of the array, Since .splice(n, 0, ...), it doesn’t remove anything, but it still has to return an array, so it returns an empty one.

Maybe you intend to return newarr2 after splicing?

1 Like

Why this isn’t working ? Except the thing that I haven’t used slice in it?

function frankenSplice(arr1, arr2, n) {
 const a1=[...arr1];
  const a2=[...arr2];

    
  a2.splice(n,0,a1);
//console.log(a2);
//console.log(arr1);
//console.log(arr2);
          return a2;
}

This tool should help you find the answer: http://pythontutor.com/visualize.html#mode=display

1 Like

I have used this tool to visualize the execution of code but couldn’t got the answer yet, why it’s not correct?

look at the value of a2 after you use splice: it becomes a two dimensional array

1 Like

function frankenSplice(arr1, arr2, n) {
const a1=[…arr1];
const a2=[…arr2];

a2.splice(n,0,…a1);
//console.log(a2);
//console.log(arr1);
//console.log(arr2);
return a2;
}

But I am not understanding why the same code is working when I am passing a1 with spread operator in splice ? Please explain this.

splice can take as many arguments as needed and will add all of them in the array

the difference between the two is given by the spread operator. a1 is an array, and it is the array that is added to the other array. if you use the spread operator this will unpack the array, and it works as if each element of the array is an argument for the splice method: in this way the splice method is adding the elements of the array to the other array (instead of a single array)