Algorithm Scripting: Slice and Splice Challenge

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?

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]

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!

1 Like

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

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.

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.