Algorithm Scripting: Slice and Splice loops

Tell us what’s happening:
why my code cant give me the correct answer
any help please?

Your code so far

function frankenSplice(arr1, arr2, n) {
let x = arr2.slice(0);
for(let i = 0 ; i < x.length; i++){
   return [x.splice(n,0),...arr1,...x]


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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36.

Challenge: Slice and Splice

Link to the challenge:

The if logic inside the loop is wrong. Challenge is to insert to elements of first array at n index of the second array. If you console the output you’ll see that your comparison logic is incorrect. You don’t have to compare elements but look for the n index in the second array.

You can solve it in a single line using spread operator and slice method as follows. (I’ve blurred it)

function frankenSplice(arr1, arr2, n) {
  return [...arr2.slice(0, n), ...arr1, ...arr2.slice(n)];

Explanation of my approach
  • ...arr2.slice(0, n) will return elements upto nth index (excluding n) & will spread the elements. So now we’ve reached the nth index of the arr2. Now we can put the entire arr1 after it.

  • ...arr1 will spread the elements.

  • ...arr2.slice(n) will start slicing from n index upto the length of the arr2.

1 Like