# Splice and Slice (Help question)

Alright so I have made a copy of the second array with the slice function and have assigned it to newArr.I made the loop for the first array, and now I’m attempting to splice the first array with the index. I know I have to increment the index with n++? Any suggestions, because its showing me an empty array on my console. Thanks!

``````
function frankenSplice(arr1, arr2, n) {
let newArr=arr2.slice(0)
let newArr2=0
for (let i=0;i<arr1.length;i++) {
newArr2=newArr.splice(n,arr1[i])

}
return newArr2;
}

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

``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36`.

Challenge: Slice and Splice

This may be good to review here.

You can use the .splice method on its own, and it will mutate the array. When you give a return value by assigning newArr2 to the splice method, you will be assigning newArr2 to the deleted values that are returned by calling the method.

Do you want to just mutate the newArr array? If that’s so, then you can just call newArr.splice(n, arr1[i]) without assigning it to another value.

I have trouble understanding what you are trying to do, but I’d recommend in general for debugging that you use console.log statements in your code wherever you feel you are missing key information.

Hello!

One of the problems your algorithm has is that `newArr.splice(n, arr1[i])` is deleting `arr1[i]` elements instead of just the `i` elements.

Using your algorithm, and taking the initial setup as the test array:

``````// arr1 = [1, 2, 3]
// arr2 = [4, 5, 6]
// n = 1
let newArr = arr2.slice(0); // OK
// newArr = [4, 5, 6];

// Inside the loop *
// i = 0;
// arr1[0] = 1
newArr2 = newArr.splice(1, 1);
// newArr2 = [5, 6]
// newArr = [4], remember that splice modifies the array

// Next iteration
// i = 1
// arr1[i] = 2
newArr2 = newArr.splice(1, 2);
// newArr2 = []
``````

As you can see, you’re actually returning an empty array.

3 Likes

I appreciate the info, I actually went back to MDN docs on splice and realized that I forgot to add the deleteCount integer in the splice. Which was the 0 in `newArr.splice(n,0,arr1[i])`. Here is the passed code:

``````function frankenSplice(arr1, arr2, n) {
let newArr=arr2.slice(0)
for (let i=0;i<arr1.length;i++) {
newArr.splice(n,0,arr1[i])
n++

}

return newArr;
}

console.log(frankenSplice([1, 2, 3], [4, 5, 6], 1));
``````
1 Like