Slice and Splice - Help Needed

Slice and Splice - Help Needed
0.0 0

#1

I’m stuck on this challenge. Could someone please provide the Complete Solution (not hints or links to other pages) followed by a brief description of how/why that solution works? I’ve already tried like 100 different methods including using the spread operator, splicing the contents of arr1 into arr2, creating a 3rd array that has the contents of arr1 + arr2, etc etc and haven’t been able to pass all the tests yet. Thanks!

Your code so far


function frankenSplice(arr1, arr2, n) {


  return arr2.splice(n,0,arr1);
}

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/66.0.3359.181 Safari/537.36.

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


#2

I found the solution from an old post for anyone who is stuck on this challenge as well. Here it is:

function frankenSplice(arr1, arr2, n) {
var arr1Copy = arr1.slice();
var arr2Copy = arr2.slice();
for (var i=0; i<arr1.length; i++){
arr2Copy.splice(n,0,arr1Copy[i]);
n++;
}
return arr2Copy;
}

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


#3

Here was my initial code that checked off everything off the list except for
“The second array should remain the same after the function runs.”

function frankenSplice(arr1, arr2, n) {
// It’s alive. It’s alive!
arr2.splice(n,0, …arr1);
return arr2;
}

this code worked for everything but it would permanently alter the arr2. The challenge has me making sure that I dont alter the original arrays provided.

The solution was, simply slicing them into a whole new arrays, which I found in the forums.

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

function frankenSplice(arr1, arr2, n) {
// It’s alive. It’s alive!
var array1 = arr1.slice();
var array2 = arr2.slice();
array2.splice(n,0, …array1);
return array2;
}

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


#4

function frankenSplice(arr1, arr2, n) {
let arr3 = [];
arr2.forEach(el => arr3.push(el));
arr3.splice(n,0, …arr1);
return arr3;
}

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