Slice and Splice question

Tell us what’s happening:
Hello, I cannot figure out what I am doing wrong on this problem. I tried to decrement the i on the for loop so the splice function does its job properly, but I am not sure what is wrong.

Your code so far


function frankenSplice(arr1, arr2, n) {
  var arr1b=arr1;
  var arr2b=arr2;
  for (var i=arr1b.length;i>0;i--) {
  arr2b.splice(n, 0, arr1b[i])
  
  }
  return arr2b;
}

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

Your browser information:

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

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

You for loop is off by one index. Try this.

for (var i=arr1b.length-1;i>=0;i--)

I don’t think you are making real copies of your parameter arrays. I think you were just assigning a second variable name to each one of them. So you cannot fulfill the requirements at the very end that you do not change either of the arrays

Because the code is not doing what you think it is here

var arr1b=arr1;
var arr2b=arr2;

This does not copy the values of arr1 into arr1b. It simply points a reference to arr1.

In other words:

  • arr1 points to an array
    • if you modify arr1, you modify the array
  • arr1b points to arr1
    • if you modify arr1b, you’re modifying arr1, which modifies the array

This is because javascript passes all funtions, arrays and objects as reference, and not value. That means you need to clone all arrays and objects if you don’t want to mutate the original.

Look at this repl to see it in action.

Here’s a nice article explaining it very well, if you want more info https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0

Okay, I have checked the answers and this is what I have come up with, so that I do not use referencing. It could really help if you could actually see what the code is returning when executed, like in the old layout. Or I just don’t know how to do it.

function frankenSplice(arr1, arr2, n) {
  var arr1b=JSON.parse(JSON.stringify(arr1));
  var arr2b=JSON.parse(JSON.stringify(arr2));
  for (var i=arr1b.length-1;i>0;i--) {
  arr2b.splice(n, 0, arr1b[i])
  
  }
  return arr2b;
}

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

That’s actually a very resourceful solution to preserving your passed arrays. Your copies are DEEP copies so even nested arrays are truly cloned. Some serious Javascript badassery!

It does not appear that your for…loop for inserting is working quite right though. The order is correct but the first element of the inserted array is missing. I believe you have a “off by one” error in your test condition i > 0.