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

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:

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

  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.

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:
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);


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

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