Slice and Splice - Correct results but failing

Tell us what’s happening:
Hi again,

I’m a bit confused on this one. It appears that I get the correct results (I tried it with each of the test arrays given) and yet I’m still failing the exercise. Is there some reason why this might be happening?

Your code so far


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

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

Your browser information:

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

Link to the challenge:

Hi there,

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

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

First of all the first variable you defined does not change the array at all i.e. newArr1 is the same as arr1. But that isn’t why your code isn’t working.

A good way to debug and figure out why it’s not working is by using google dev tools>sources>New snippet.

If you run your code in the console you would notice that your code gives a nested array so you have to flatten it. An elegant method is using the spread operator by putting three dots (…) before the array that you want to flatten.

Hope that helps.

Let me know if you need anymore help.

Hey @LDN - thanks for the help. After doing a bit of research I came across array.prototype.flat() and that seemed to solve most of the issue of the array flattening. I tried a few different methods of using the spread operator like you suggested, and I can’t figure out exactly where or what you mean. Could you please elaborate?

I wrote newArr1 to take a slice of arr1 which would change depending on the length to allow arrays with variable lengths to be passed, and assigned that to newArr1 so that arr1 was not mutated. I understand it’s not necessarily doing anything to modify the array, but the hope is that it would be variable that could accept any length thats input into the parameter.

  let newArr1 = arr1.slice(0, arr1.length);// It's alive. It's alive!
  const newArr2 = arr2;
  newArr2.splice(n, 0, newArr1);
  return newArr2.flat();
}

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

The issue I’m still having is that its saying that arr2 is mutated after the script has run. I don’t quite understand why this is happening. Are any changes applied to newArr2 also being applied to arr2? If so, why is that the case?

Thanks!

This is not a copy of arr2, it is just a change of reference. To copy you need to use concat, slice or the spread operator

Plus here:

You are adding the whole of newArr1 to newArr2 when you should add its elements (this is a good use case for the spread operator)