DEV Community

Randy Rivera
Randy Rivera

Posted on

Using slice() and splice()

function frankenSplice(arr1, arr2, n) {
  return arr2;
}

frankenSplice([1, 2, 3], [4, 5, 6], 1);
Enter fullscreen mode Exit fullscreen mode
  • Here You are given two arrays and an index.
  • Let's Copy each element of the first array into the second array, in order.
  • We begin inserting elements at index n of the second array.
  • Then you should return the resulting array. The input arrays should remain the same after the function runs. ####Hint:
  • The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
  • The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place

  • Answer:

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

console.log(frankenSplice([1, 2, 3], [4, 5, 6], 1)); // will display [4, 1, 2, 3, 5, 6];
Enter fullscreen mode Exit fullscreen mode

Top comments (0)