Array.splice method in JavaScript

Array.splice() is a built-in method in JavaScript that allows you to modify an array by removing or replacing existing elements and/or inserting new elements at a specific index.

The syntax for Array.splice() is as follows:

array.splice(startIndex, deleteCount, item1, item2, ...)
  • startIndex: The index at which to start changing the array. If negative, it specifies an offset from the end of the array. For example, -1 means the last element of the array.
  • deleteCount: The number of elements to remove from the array. If set to 0, no elements will be removed.
  • item1, item2, ...: The elements to add to the array, beginning at the startIndex. If no elements are specified, deleteCount elements will be removed from the array.

The splice() method modifies the original array and returns an array containing the removed elements. If no elements are removed, an empty array is returned.

Here are some examples of using Array.splice():

const array = ['a', 'b', 'c', 'd'];

// Remove one element at index 2
const removed = array.splice(2, 1);
console.log(array); // Output: ['a', 'b', 'd']
console.log(removed); // Output: ['c']

// Replace two elements starting at index 1 with 'x' and 'y'
const replaced = array.splice(1, 2, 'x', 'y');
console.log(array); // Output: ['a', 'x', 'y', 'd']
console.log(replaced); // Output: ['b', 'd']

// Insert two elements starting at index 1
array.splice(1, 0, 'p', 'q');
console.log(array); // Output: ['a', 'p', 'q', 'x', 'y', 'd']

In the first example, Array.splice() removes one element at index 2 ('c') and returns it in the removed array.

In the second example, Array.splice() replaces two elements ('b' and 'c') starting at index 1 with 'x' and 'y', respectively. The replaced array contains the removed elements ('b' and 'c').

In the third example, Array.splice() inserts 'p' and 'q' starting at index 1, effectively shifting the remaining elements to the right.