Slice and Splice without a for loop

In answering this question, I proposed this answer:


function frankenSplice(arr1, arr2, n) {
  let arrHold1 = arr1.slice(0,(arr1.length));
  let arrHold2 = arr2.slice();
  arrHold2.splice(n,0,arr1);
  var arr2 = arrHold2;
  return arr2;
}

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

Which as far as I can tell works perfectly. But the tests fail because I didn’t do it in a for loop. The quest never requires a for loop, so why isn’t my answer valid?

browser information:

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

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

You are not coping the elements of one array into another, you are assigning the reference of the same array to multiple variables.

Your answer does not work, you’re splicing in the whole copy of array1 rather than the values from it, so the result of the console log example there is:

[ [ 1, 2, 3 ], 4, 5, 6 ]

Also what @MatteoCarotta said, you’re doing it for both arrays. You copy them fine, but then you overwrite the existing ones instead of sticking with the copies.

Ohhhhhh!! lightbulb

Thank you both! I get it now.

1 Like