BAS: Slice and Splice: Passing All But One Check, Please Help

BAS: Slice and Splice: Passing All But One Check, Please Help
0.0 0

#1

I’m doing the Slice and Splice challenge at the moment, and my code is currently passing all of the checks except for “All elements from the first array should be added to the second array in their original order.” Could someone help me figure out why? Here’s the code:

function frankenSplice(arr1, arr2, n) {
  // It's alive. It's alive!

  let newarr2 = arr2.slice();

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

  return newarr2;
}

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

#2

I ended up passing the challenge in a different way, but I would still like to understand why that code wouldn’t work for it, if anyone has an answer.


#3

If you consider the following call to the function, your code results in [4, 5, 1, 2, 3, 6], but it should return [ 4, 1, 2, 3, 5, 6].

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

Your -n as the first argument value of the splice, means it will be -1. An index of -1 for splice means start the insertion at the last index for the splice. newarr2 is [4, 5, 6], so the splice will start at index -1 (which is the last index (2) ), so 1, 2, 3 gets inserted in at index 2 and the 6 gets shifted to the end.