slice.splice function code example

Example 1: javascript slice vs splice

var array=[1,2,3,4,5]
console.log(array.slice(2));
// shows [3, 4, 5], returned selected element(s).
 
console.log(array.slice(-2));
// shows [4, 5], returned selected element(s).
console.log(array);
// shows [1, 2, 3, 4, 5], original array remains intact.
 
var array2=[6,7,8,9,0];
console.log(array2.slice(2,4));
// shows [8, 9]
 
console.log(array2.slice(-2,4));
// shows [9]
 
console.log(array2.slice(-3,-1));
// shows [8, 9]
 
console.log(array2);
// shows [6, 7, 8, 9, 0]

Example 2: use of slice and splice add elements array

function frankenSplice(arr1, arr2, n) {
  // Create a copy of arr2.
  let combinedArrays = arr2.slice()
  //                   [4, 5, 6]

  // Insert all the elements of arr1 into arr2 beginning
  // at the index specified by n. We're using the spread
  // operator "..." to insert each individual element of 
  // arr1 instead of the whole array.
  combinedArrays.splice(n, 0, ...arr1)
  //                   (1, 0, ...[1, 2, 3])
  //                   [4, 1, 2, 3, 5, 6]

  // Return the combined arrays.
  return combinedArrays
}

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