Tell us what’s happening:
Your code so far
function frankenSplice(arr1, arr2, n) {
// It's alive. It's alive!
let copyArr1 = arr1.slice(0);
let copyArr2 = arr2.slice(0);
copyArr1.forEach((x)=>copyArr2.splice(n,0,x));
return copyArr2;
}
frankenSplice([1, 2, 3], [4, 5], 1);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/slice-and-splice
Can someone tell me why the result of arr1 is reversed???
I got the result as [ 4, 3, 2, 1, 5 ]
Many thanks.
Let’s think about what we are trying to achieve with this function:
copyArr1.forEach((x)=>copyArr2.splice(n,0,x));
We’re taking copyArr1
which contains arr1
and iterating or running through each element it contains. Each time you iterate an element you’re splicing that element at nth index of copyArr2
containing arr2
Loop
[1,2,3]
^
Add element to index 1 with copyArr[0] at second index without deleting any elements after
This will put the element at the second index of copyArr2
: [ 4, 1, 5 ]
The second iteration will do the same thing by adding copyArr1[i]
to the second index again:
[ 4, 2, 1, 5 ]
Are you starting to see the pattern? The index isn’t changing to accomdate the order of copyArr1
hence the reverse effect you’re encountering.
So the trick will be how would you go about determining the next index is to properly insert arr1
elements in the correct order? I’ll give you a hint and point you to the forEach()
docs on mdn:
The truth lies in what parameter passing with forEach()
and how you use it.
OH!!! I understand it now!!! Thank you so much!.
Before reading your answer, I just simply used copyArr1.reverse()
before running copyArr1.forEach()
.
I think I know how to modify it in another way. Thank you!!