Slicing and splicing

Tell us what’s happening:
Describe your issue in detail here.
why do I have to create a new array to splice the arr1 into arr2.
I thought arrays in JS are mutable.

ex. arr2.splice(index, 0, …arr1) returns


  **Your code so far**

function frankenSplice(arr1, arr2, index) {
let localArr = arr2.slice();
localArr.splice(index, 0, ...arr1);
return localArr

console.log(frankenSplice([1, 2, 3], [4, 5, 6], 1));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36

Challenge: Slice and Splice

Link to the challenge:

From the instructions:

“The input arrays should remain the same after the function runs.”

JS Array splice function not create really new instance.
New Array impact old array.
So to create real new, you can use this expression.
let newArr = JSON.parse(JSON.stringify(oldArr));

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.