Slice and Splice challenge

Following my code bellow, the “result” is:
[ 4, 1, 2, 3, 5, 6 ]

What I’m not sure is the reason why my code doesn’t meet the requirement “All elements from the first array should be added to the second array in their original order.”


function frankenSplice(arr1, arr2, n) {
  let copy = arr1.slice(0, 3);
  let result = [];
  
  result.push(...arr2);
  result.splice(n, 0, ...copy);
  
  return result;
}

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

I even tried to use splice to add the elements 1 by 1 using a for loop:

function frankenSplice(arr1, arr2, n) {
  let copy = arr1.slice(0, 3);
  let result = [];
  
  result.push(...arr2);
  
  for (let i = 0; i < copy.length; i++) {
    result.splice(n+i, 0, copy[i]);
  }
  
  return result;
}

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

Your browser information:

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

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

1 Like

Hi @fahrenheitdlp,

In your first code piece, change arr1.slice(0, 3) to arr1.slice(0, arr1.length) . This is because the input array could be of any length, not just 3. That’s why your code was failing.
Hope this helps

1 Like

Done! My sleepy head didn’t let me see that flaw.

1 Like

From MDN: If begin is undefined, slice begins from index 0 .
So can we do it also like this, because it makes a copy of whole array.

let copy = arr1.slice();

Hi @LuigiDerson,

Yes, we can also write the code that way