Slice and Splice, add element in their original order

Tell us what’s happening:
Hi! I passed all the tests (Basic Algorithm Scripting: Slice and Splice) except one:

All elements from the first array should be added to the second array in their original order.

Can’t understand what’s the issue here. Any idea?

Your code so far


function frankenSplice(arr1, arr2, n) {
  let localArray = arr2.slice();
  arr1.forEach(function(item, index) {
    localArray.splice(-n, 0, item);
  });
  // It's alive. It's alive!
  return localArray;
}

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

your code result is 4,5,1,2,3,6
instead you need to start adding at index 1, so it should result in 4,1,2,3,5,6

what do you want to do with the -n in localArray.splice(-n, 0, item);? With that you start counting the index from the end of the array. you need to do a little change there for things to work here (but it will not pass other tests, so you may want to try something else - different length means that the nth item from the end is different even for the same n. you may want to try something else for which you count from the beginning of the array)

1 Like

This one seems to work. Thank you!

function frankenSplice(arr1, arr2, n) {
  let localArray = arr2.slice();
  let reversed = arr1.slice().reverse();
  reversed.forEach(function(item, index) {
    localArray.splice(n, 0, item);
  });
  return localArray;
}

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