Help - Slice and Splice

Hi,

I didn’t know how to use splice() so I used other ways to solve the problem.
what did I do wrong here?


function frankenSplice(arr1, arr2, n) {
let result = [];
let array1 = arr1.toString();
let array2 = arr2.toString();

for (let i = 0; i<array1.length; i++){
for (let j = 0; j<array2.length; j++){
  if (array1[j] == n){
     return result += array2[j] + array1 + array2.slice(1);
      }
   }
}
   return result;
}

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


It should return [4, 1, 2, 3, 5], however my code returns [41,2,3,5].
I wanted to do arr1.split() so there will have a comma between 4 and 1, but it says arr1.split is not a function.

I feel like I am so close to the answer but also feel that my logic could be totally wrong.

Please help, thank you!

Link to the challenge: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/slice-and-splice

You should create a separate copy of arr2, and use a for loop to insert values of arr1 in the arr2 clone with splice method.

Hi could you please explain it more?

So create a separate copy of arr2 using the slice method because the challenge does not want you to mutate it.

Now using a for loop, insert values of arr1 into arr2 with splice method, starting at n.

Increment n after each splice to put it in the corresponding index.
Let me know if you still need help.

Another way to copy the array is to use the spread operator. It was one of the previous exercises under Basic Data Structures: Copy an Array with the Spread Operator leading up the point of this current one.

yes, I just learned how to use splice() and spread operator together to solve this problem, it’s much simpler.

what do you think is the value of array1 here?

you can look at what happens with a tool like this: Online JavaScript Compiler, Visual Debugger, and AI Tutor - Learn JavaScript programming by visualizing code

let array1 = arr1.toString(); // returns 1,2,3

and it’s a string, then you are looping through a string, until a character in the string is equal to n

it’s not exactly what you want to get

try looking at your code with that tool

Thank you! I will take a look with that tool