Slice and Splice ... having trouble

Tell us what’s happening:
the element of arr1 aren’t being copied in the proper order, can anyone tell me why that is ?

Your code so far


function frankenSplice(arr1, arr2, n) {
let arr3 = arr2.slice(0);
for(let i = 0; i < arr1.length; i++){
  arr3.splice(n, 0, arr1[i]);
  console.log(arr3);
}
return arr3;
}

frankenSplice([1, 2], ["a", "b"], 1);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36.

Challenge: Slice and Splice

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

for(let i = 0; i < arr1.length; i++){
  arr3.splice(n, 0, arr1[i]);
  console.log(arr3);
}

In this block of code, you’re updating i for each iteration of the loop, but what about n? Think about the index at which you want to insert a new element from arr1 during each iteration.

i wasn’t incrementing the n and that’s why the elements were being added at the same position

1 Like