Doubt about the use of the loop for-in in the exercise "Slide and Splice"

Greetings. I’d been practicing with the exercises of Basic Algorithm Scripting and I couldn’t make it works with a for-in loop.
I think that the for-in loop was working in reverse because the ouput was “4,3,2,1,5,6”. But, I don’t have any idea why so, I want to read your opinions.
Sorry for my english, I’m working it too. :slight_smile:

Your code so far


function frankenSplice(arr1, arr2, n){
  let localArr = arr2.slice();
  for( let elem in arr1){
    console.log(elem)
    localArr.splice(n,0,arr1[elem]);
  }
  console.log(localArr);
  return localArr;
}

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

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

you are putting the elements one by one at index 1
so the starting array is [4,5,6]
first element added and it becomes [4,1,5,6]
now there is a 2 to add, again at index 1: [4,2,1,5,6]
then there is a 3 to add, again at index 1: [4,3,2,1,5,4]

and that’s why you have the items added in reverse order

1 Like