Slice and Splice reversing the array

Tell us what’s happening:

hello
I am so confused to why the array that is inserted in another one is being reversed. I am so confused. can somebody shed some light to this statement? thank you in advance

Your code so far


function frankenSplice(arr1, arr2, n) {
    let zero = 0;
    //arr2 = arr2.splice(n, zero, arr1)
    // go through the array and add it in arr2
    for (let counter = 0; counter < arr1.length; counter++) {
        arr2.splice(n, 0, arr1[counter]);
    }
   return arr2;
    //    return arr2;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/slice-and-splice

In your splice method, you are indicating index 1 from arr2 in your range for splice, and for the second argument, you’re specifying how many items to remove, so you are removing 0, from arr2 itself.

So instead, for the first iteration of your for loop, you are taking the first index of arr1, and inserting it between index 1 of arr2. And since you didn’t remove any items in the splice method, your 5 and 6 are still intact, thus giving you this array for the first iteration of the for loop.

[4, 1, 5, 6]

On the second iteration, you’re repeating the same exact process, except the new index is at 1. So now 2 is being spliced out and inserted into array 2 after position one. And you kinda get the idea, it will keep repeating this process, until it has done reached the length of arr1. Giving you the reversed result that you are seeing.

[4, 3, 2, 1, 5, 6]

yeah ok that makes sense

It can be super confusing given what’s being taken place in the for loop. Writing each step down on a piece of paper or something definitely helps out in seeing how the array is being formed, given that you know what each parameter of your splice method is doing.