Home > database >  Inserted array shows in reverse JS
Inserted array shows in reverse JS

Time:05-20

I am just starting to learn js and as many (I'm sure) I am facing problems lol. I am trying to copy an array into another array at a designated index location.

I seem to be able to do everything correct but when I log the result, the inserted array shows in reverse and I have no idea why¿?¿?.

Have also tried a .forEach as looping method, but I'm still a bit green to use it right.

This is the code:

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

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

It logs // [ 4, 3, 2, 1, 5, 6 ] instead of the desired out: [ 4, 1, 2, 3, 5, 6 ]

CodePudding user response:

You are inserting the elements at the same index, so after inserting 1 you insert 2 at the same position, shifting back the 1 and all following elements. Either iterate backwards over arr1 or increment n after each iteration like I have done here.

function frankenSplice(arr1, arr2, n) {
  let newArr = arr2.slice([]);
  for (let i = 0; i < arr1.length; i  ) {
    newArr.splice(n, 0, arr1[i]);
    console.log(newArr)
    n  ; // add this
  }
}

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

  • Related