Slice and Splice - inserting each element separately

Slice and Splice - inserting each element separately
0.0 0

#1

Tell us what’s happening:
I am stuck at this challenge and would appreciate any advice! So far my code looks like this:

function frankenSplice(arr1, arr2, n) {
var arr3 = arr2.slice(0);
arr3.splice(n, 0, arr1);

return arr3;
}

when I run it on the console I can see that I am inserting the first array at the position n so I am not inserting each element separately. I’ve also tried to use a for loop and the code worked for strings since I changed the values with toString method but it still wouldn’t work for numbers.
Thanks so much!

Your code so far


function frankenSplice(arr1, arr2, n) {
var arr3 = arr2.slice(0);
arr3.splice(n, 0, arr1);

return arr3;
}


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

Your browser information:

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

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


#2

You are close, but you need to read the splice documentation regarding the arguments after the first (start) and second (deleteCount), because you can not just add an array (arr1), because it is expecting individual elements. Think about a special syntax you learned in the ES6 section that would help you separate arr1 into its elements to pass as extra arguments to the splice function.


#3

Thank you so much for your reply. It’s very helpful! I’m working through ES6 section right now so hopefully will solve this challenge once I’m finished with ES6!


#4

look for the … spread operator in ES6, i was looking for 1 line solution but it returns empty array, below solution works aswell.

----solution----

function frankenSplice(arr1, arr2, n) {
    const newArr = arr2.slice(0);
    newArr.splice(n, 0, ...arr1);
    return newArr;
}

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

#5

Thank you, Farhankk!