My solution:
function frankenSplice(arr1, arr2, n) {
// It's alive. It's alive!
let a=[];
a=arr2.slice();
a.splice(n,0,arr1);
console.log(a); // The following 3 lines are for testing purpose only.
console.log(arr1);
console.log(arr2);
return a;
}
I have checked my program,for all types of input,and it holds correct,however the compiler in FCC is throwing error. Please check the reasons.
**Note:The code works.**
The question for reference:
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.
Check your output again, it is not correct. You have a nested array.
frankenSplice([1, 2, 3], [4, 5], 1)
// You are returning [4,[1,2,3],5]
// Should return [4, 1, 2, 3, 5]
You need to either loop the array to get to the elements inside or use the spread operator. Another option is to flatten the array before returning it.
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-the-spread-operator-to-evaluate-arrays-in-place/
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/copy-an-array-with-the-spread-operator/
Also please link to the challenge when asking for help.
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/slice-and-splice/
2 Likes