Slice and Splice (algorithms)

Hi Campers,

While passing the task Basic Algorithm Scripting: Slice and Splice I’ve faced with such a difficulty:

This code works fine:

function frankenSplice(arr1, arr2, n) {
  let newArr = arr2.slice();
  newArr.splice(n, 0, ...arr1);
  return newArr;
}

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

While this is not:

function frankenSplice(arr1, arr2, n) {
  let newArr = arr2.slice();
  return newArr.splice(n, 0, ...arr1);
}

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

Could you please explain me:

  1. Why?
  2. The difference in both approaches.
1 Like

Hello
because the splice() method does not return the modified array, but :
An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.
source :

2 Likes

Thank you!

Somehow I’ve missed it.

you are welcome Camper