Question for basic algorithm - Slice() and Splice()

``````function frankenSplice(arr1, arr2, n) {

let localArray = arr2.slice();

for (let i = 0; i < arr1.length; i++) {
localArray.splice(n, 0, arr1[i]);
n++;
}
return localArray;
}
``````

Hello everyone ! I can’t understand why we need to increment the n index to get the right order of arr1, i tried without n++, it gave me a result with arr1 values in reverse. Can someone explain why ? Thanks in advance !

Because the length of the array is increasing.

You add the element first at “n” then the second at “n+1”…

1 Like

Reasoning about indexing into an array that you mutate as you loop over the arry can get messy. I usually recommend against that sort of thing.

3 Likes

As we know that `splice` mutates the `localArray` for each iteration in the form loop, and also from the code I can see that the localArray grows in size by 1 for every `i++`.

Hope this pseudocode below helps you understand the issue clearer.

``````Given arr1 = [1,2,4] and arr2 = [3,5,6]
localArray = [3,5,6]
localArray now equals  [ 3,5,1,6]
if i = 0 and n = 2 then arr[i] = 1 so localArray.splice(2, 0, 1) equals [ 3,5,1,6]
next, if i = 1 and n = 3 then arr[i] = 2 so localArray.splice(3, 0, 2) equals [ 3,5,1,2,6]
``````

Let’s say that if you were to take away the `n++`, then the pseudocode would look like this:

``````Given arr1 = [1,2,4] and arr2 = [3,5,6]
localArray = [3,5,6]
if i = 0 and n = 2 then arr[i] = 1 so localArray.splice(2, 0, 1) equals [ 3,5,1,6]
localArray now equals  [ 3,5,1,6]
next, if i = 1 and n = 2 then arr[i] = 2 so localArray.splice(2, 0, 2) equals [3,5,2,1,6]
``````

Keep in mind that while `n` remains unchanged, the indexed number in the array (`arr[n]`) does change.
Now this should be clear that without the `n++` thingy, it would produce the effect that you’ve been wondering about.

1 Like

Explicit and detailed, thanks so much !

1 Like

My pleasure man. HMU with ur future questions.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.