Spread operator and splice

Tell us what’s happening:
I am working on the splice problem, where you insert the contents of one array into another. The main trouble I’m having is getting splice to work properly. It isn’t responding to adding elements in general, as I’ve tried returning something along the line of sth.splice(1, 0, 7) from the function, and still obtain an undefined array. Any help would be appreciated.
I guess, a related question is if there is a way use the spread operator directly in splice.

Your code so far

function frankenSplice(arr1, arr2, n) {
  // It's alive. It's alive!
  let sth = arr2;
  return sth.splice(...[n, 0].concat(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/72.0.3626.121 Safari/537.36.

I believe you need to return the array not the splice itself.

Thank you. Morning delirium.

This is not copying the array, in case that is what you wanted to do. So you are actually changing the input array

yes, thank you; that is what i wanted to do. ended up spreading it.

You can also use concat() (let copy = arr.concat([])) or slice() (let copy = arr.slice()) - spreading is a wonderful way of copying.

1 Like