Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
question:

You are given two arrays and an index.

Copy each element of the first array into the second array, in order.

Begin inserting elements at index n of the second array.

Return the resulting array. The input arrays should remain the same after the function runs.

my code is:

JavaScript
<pre>unction frankenSplice(arr1, arr2, n) {
 let newarr = arr2;
  
  newarr.splice(n,0,...arr1);

  console.log(arr2);
  console.log(newarr)
  
  return newarr;
}

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



What I have tried:

I would like arr2 keep the same, but after assign to newarr, arr2 got same values newarr has.
Posted

1 solution

There's a small mistake in your code. The splice method modifies the array in place and returns an array containing the deleted elements. You need to insert one array into another, so all you need is a single splice. Here is the modified version of code:
JavaScript
function frankenSplice(arr1, arr2, n) {
  
  // Create a shallow copy of arr2 to avoid modifying it directly
  let newarr = arr2.slice();
  
  newarr.splice(n, 0, ...arr1);

  console.log(arr2);
  console.log(newarr);

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

Reference: https://stackoverflow.com/questions/58209968/how-to-use-splice-and-slice-to-put-an-array-into-another-array[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900