Failing last test on Slice and Splice

Failing last test on Slice and Splice
0

#1

function frankenSplice(arr1, arr2, n) {

let newArr = arr2;
for (var i = 0; i < arr1.length; i++) {
newArr.splice(n+i, 0, arr1[i]);
}

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

I’m getting the right output but my arr2 is being altered and I’m not understanding why. I thought by creating the var newArr I would no longer be altering arr2…?


#2

splice()modifies the array it is called on.


#3

Your code actually makes two variables pointing to the same array - major point of confusion that is common to many programming languages. Javascript assigns objects (which includes arrays) by reference.

Since your array is only one level deep you could make a shallow copy or you could find a way to create newArr so that your parameter array is not altered.


#4

You know I got confused, when I searched for slice on MDN I found string.prototye.slice() and didn’t realize it could be called on an array also! This allowed me to create a copy in my var and pass the last test. Thanks!


#5

my solution

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

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


#6

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

If you want to compare your solution to others, use the Get a hint button on the challenge and there are alternative solutions you can compare yours to. Also, you can probably search older posts using the forum search feature or google the challenge name and find more there.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

Thank you for understanding.


#7

My bad. I just didn’t find solution similar to mine so I thought I was helping. I understand now that’s not how it works. Thanks for letting me know :slight_smile:


#8

No worries. Happy coding!