Basic algorithm scripting : slice and splice [solved]

Here is my solution of this test :

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

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

Does anybody see mistake in it? I have compared this to the ‘Get A Hint’ and various posts of same topic in this camper forum, i’m pretty sure this is already correct, but the curriculum seems adamant not to let me pass the test.

The problem is that splice returns an array of the items deleted. Since you are adding items, it returns an empty array. The solution is to write the splice function on a separate line from the return statement. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice for more on splice.

1 Like

Thank you, solved. I tried chaining the splice and splice method in a single line, but it didn’t work :smile:. Well, i guess the shortest solution is three lines afterall.

How did you solve the problem???
I was doing the same way like you but didnt work?

splice returns the removed items and modify the array on which it is applied
so if you write:

let arr = [0,1,2,3];
let a = arr.splice(0,2);

a is now equal to [0,1] and arr is equal to [2,3]

applied to the challenge, return frankenstein.splice(n,0,...arr1); is not returning the new array.

In debugging, instead of returning something, try first to console log it (console.log(frankenstein.splice(n,0,...arr1))) and see what’s actually the value your function is returning