Slice and Splice. What's Wrong with my Code?

Slice and Splice. What's Wrong with my Code?
0

#1

I have no idea what I’m doing wrong. When I log all the answers to the console, everything looks good. The console exactly reflects the expected answers. Can anyone guide me here?

function frankenSplice(arr1, arr2, n) {
// It’s alive. It’s alive!
let arr3 = arr2.slice();
arr3.splice(n, 0, arr1.slice());
console.log(arr3);
return arr3;
}
frankenSplice([1, 2, 3], [4, 5], 1);
frankenSplice([1, 2, 3], [4, 5, 6], 1);
frankenSplice([1, 2], [“a”, “b”], 1);
frankenSplice([“claw”, “tentacle”], [“head”, “shoulders”, “knees”, “toes”], 2);


#2

Hello ,
Look this example you will get easy understand the topic of Slice and splice

https://www.w3schools.com/jsref/jsref_splice.asp for splice

https://www.w3schools.com/jsref/jsref_slice_array.asp For slice

Hope this help this.


#3

Thanks for the references, but I’d already been through those.

I figured out what was wrong anyway.

In my original code, I was inserting a copy of arr1 into arr2 instead of inserting the array itself.

Here’s my new code:

function frankenSplice(arr1, arr2, n) {
// It’s alive. It’s alive!
let arr = arr2.slice(0);
arr.splice(n, 0, …arr1);
console.log(arr);
return arr;
}

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

Thanks for your reply @SpadeX.


#4

Well !!! Your great man, you understand it.