Hi! At the time, I’m in this challenge of the javascript certificate:
You are given two arrays and an index.
Copy each element of the first array into the second array, in order.
Begin inserting elements at index n of the second array.
Return the resulting array. The input arrays should remain the same after the function runs.
So my solution was this:
function frankenSplice(arr1, arr2, n) {
let secondArr = arr2.slice()
for (let values of secondArr) {
if (secondArr.indexOf(values) === n) {
secondArr.splice(n, 0, ...arr1)
}
}
return secondArr
}
I know that’s not the best way to do it, it’s just that I focus on solving the problem first and then work my way backwards to make it more redable/efficient. Now the thing is, the above function passed all the test except for the condition that: “All elements from the first array should be added to the second array in their original order.”
Wich is find a bit weird because all the test cases were positive. I eventually reduced the code to this:
function frankenSplice(arr1, arr2, n) {
let secondArr = arr2.slice()
secondArr.splice(n, 0, ...arr1)
return secondArr
}
And this worked…
Clearly it has something to do with my for…of loop, but just wanted to know why. Thanks beforehand!