What I doing wrong?

The output is correct, but the following requirement is not met and it is not letting me complete the challenge:

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

  **Your code so far**

function frankenSplice(arr1, arr2, n) {
let newArray = [];

for (let i=0; i < arr2.length; i++){
  newArray.push(arr2[i])
  
  if(i==n-1){
    for (let x=0; x < arr1.length; x++) {
      newArray.push(arr1[x]) 
      
    }

  }
}
arr2 = newArray
return arr2;
}

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/90.0.4430.85 Safari/537.36.

Challenge: Slice and Splice

Link to the challenge:

what happens if arr2 is empty?

you actually need to use slice and splice here, not a loop

Why? Why not return newArray?

slice and splice are not needed to solve this challenge, though they do make it simpler.

You can create an empty array to represent the final array. Next, iterate up to (not including) arr2's index that is equal to n and push each of those elements into the final array. Then, you would iterate through all of arr1's elements and push them to the final array. Finally, you would start at the index equal to n of arr2 and go to the end of arr2 and push all of those elements into the final array.

This allows you to achieve the desired final array without mutating the original input arrays.

Criteria:

The first array should remain the same after the function runs.

The second array should remain the same after the function runs.

What happens to arr2 in the closing lines of your code?

And yes, I also did this without splice and slice, but having subsequently looked at the suggested answers after completing it, its worth spending a few mins looking back at them for future use

Nothing happens to arr2. I only iterate over it from the index equal to n up till the end to get the remaining elements needed to complete the splice.

I was referring to the original code submitted

Sorry about that. I mistakenly thought you were the OP.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.