# Algorithm Scripting: Slice and Splice Challenge

Algorithm Scripting: Slice and Splice Challenge
0

#1

Hi everyone,

I was hoping to get some assistance with this challenge.

You are given two arrays and an index.

Use the array methods slice and splice to 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 first solution was as follows:

``````function frankenSplice(arr1,arr2,n) {
arr2.splice(n, 0, arr1);
return arr2;
}
``````

This gave me all the correct answers it seems but still failed the challenge? So I reread the challenge and saw that the alteration should not modify the original arrays. I figured maybe my splicing was editing the originals and tried a new solution by assigning each array argument as its own variable inside the function.

``````function frankenSplice(arr1, arr2, n) {
var arrchng1 = arr1;
var arrchng2 = arr2;
arrchng2.splice(n, 0, arrchng1);
return arrchng2;
}
``````

This also did not work. When I console.log all of the tests I get the correct solution so I am confused as to why my code is failing. Could anybody point me in the right direction of what I am doing wrong?

#2

Youâ€™re splicing the array itself in, not the elements from the array. So youâ€™ll get

``````[[1,2,3],4,5,6]
``````

rather than

``````[1,2,3,4,5,6]
``````

#3

Iâ€™ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The â€śpreformatted textâ€ť tool in the editor (`</>`) will also add backticks around text.

Note: Backticks are not single quotes.

#4

Thanks Dan.

That is really obvious now that you mentioned it ha. It would be nice if the returned information on their editor was formatted as it actually is and not just the contents. Maybe that is something I am missing though.

Appreciate the help!

#5

Just for future reference, when you console log an array, what you get is the values, like you found. To get a representation of the structure, you can use `JSON.stringify` to get a string version, like:

``````console.log(JSON.stringify(myArray))
``````

#6

How do you splice the elements to look like your second example?

My results look exactly like the first code, an array within an array.

#7

You can do it a few ways, possibly the easiest to understand would be:

You have the array you want to splice into (a).
You have the array you are taking the values from (b).
You have the index you have to splice from (n).

Loop over b (so the loop counter i starts from 0).
Each iteration of the loop, splice the current value from b into a at position i + n.
Return a when youâ€™re done.