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

I was trying to solve the problem of the slice, splice algorithm.I was solved with my way and my solution is working for all steps but I don’t know why my solution doesn’t accept by system.
The task is: 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.
The first and second arrays should remain the same after the function runs.

My Solutions is :

function frankenSplice(arr1, arr2, n) {
let z = arr2.slice(0, arr2.length);

let x = arr2.splice(n, arr2.length, …arr1);

arr2.splice(arr2.length, arr2.length, …x);

let result = arr2.slice(0, arr2.length);

arr2 = z;

console.log(arr2);
console.log(arr1);

return result;
}

console.log(
frankenSplice([“claw”, “tentacle”], [“head”, “shoulders”, “knees”, “toes”], 2)
);

you are changing arr2, that alone make the tests fail

But, the last step I am reverting arr2 from z wit that code
arr2 = z;

you are assigning a new array to arr2 but are not reverting the input array

try to add the below as last thing in your editor

let input1 = [1,2,4]
let input2 = [6,8,2]

let result = frankenSplice(input1, input2, 1)

console.log({input1})
console.log({input2})
console.log({result})
1 Like

Also, the system is accepted that the below code but almost everything is same :slight_smile:

function frankenSplice(arr1, arr2, n) {

    let x = arr1.slice(0,arr1.length);
    let y = arr2.slice(0,arr2.length)

    let a = y.splice(n, y.length, ...arr1);
    console.log(y);
    console.log(a);
    y.splice(y.length,y.length,...a);
    console.log(y);
   
    return y;
}

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


in this case you are no more changing the input arrays

2 Likes

it looks a little confuse :slight_smile: But finally I understood I think so. The place of input is changed on data but clone of input is assigned to itself so it is not accepted by system…
Thanks for replies :slight_smile:

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