Slice and Splice, Spread Operator

Slice and Splice, Spread Operator
0

#1

Tell us what’s happening:
Why cannot I use the Spread Operator of the array here while adding the items to the Splice method?

Your code so far


function frankenSplice(arr1, arr2, n) {
  // It's alive. It's alive!
  let arrTwo = arr2.slice();
  let arrRe =arrTwo.splice(n,0,...arr1);
  //console.log(arrRe);
  return arrRe;
}

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

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


#2

You can use it and your function is working correctly but not as you want :slight_smile: - it is returning arrRe which in your case is an empty array. Splice is changing original array (mutable method), and result from array.splice is removed element from original array (in your case empty array is assigned to arrRe).

You want to return original array (arrTwo) not the result of its splicing.


#3

Thanks @wawraf. I completed the challenge with the below.

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

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