Basic Algorithm Scripting: Slice and Splice

Basic Algorithm Scripting: Slice and Splice
0

For this challenge, my code is passing all requirements except for: “All elements from the first array should be added to the second array in their original order.” However, when I console.log(concArr2), I seem to be getting the desired array every time. What am I doing wrong?

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

function frankenSplice(arr1, arr2, n) {
  for(let i = 0; i < arr2.length; i++){
    if(i === n){
      let arr3 = arr2.slice(0, n);
      let arr4 = arr2.slice(n, arr2.length);
      let concArr = arr3.concat(arr1);
      let concArr2 = concArr.concat(arr4);
      return concArr2;
    };
  };
};

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

Can you format your code and post a link to the challenge?

Updated it! Thank you!

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

You are not adding them to second array, but to concArr2.

Good catch! I guess the code means the same thing but doesn’t accomplish it how FCC wants. Thank you!

1 Like

I tried solving it as below

function frankenSplice(arr1, arr2, n) {
  // It's alive. It's alive!
  let arr3 = arr2;
  arr3.splice(n,0,...arr1);
  return arr3;
}

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

but FCC keeps on complaining that The second array should remain the same after the function runs. . please clarify what above solution is failing as per FCC ?

With this you are not making a copy, just a new reference to the same array, so arr2 is still getting modified.
To create a copy you need to use concat(), slice() or the spread operator

1 Like

Thanks for detailed clarification.

Regards,
Vikram