The JavaScript splice() technique replaces or removes array elements while they are still in place.
Syntax
The syntax is as follows:
removedArray = array.splice(index, count, item1......itemN)
Removed Array : The array which stores all the removed elements that the splice() method returns
Array: The array on which splice() method is being applied
Splice: Function call to the method
Index: Starting index for the splice() method
Count: Specifies the number of items in the array to replace/remove from the starting index
Items: Items that replace the array elements from the starting index
Examples
The examples that demonstrate various applications of the splice() technique are shown below.
- Eliminate all elements that come after the initial element.
var arr = ['A', 'B', 'C', 'D'];
var removed = arr.splice(1, arr.length-1);
console.log('Original Array: ', arr)
console.log('Removed Elements: ', removed)
// arr is ['A']
// removed is ['B', 'C', 'D']
- Change every element that comes after the initial element.
var arr = ['A', 'B', 'C', 'D'];
var removed = arr.splice(1, arr.length-1, 'X', 'Y', 'Z');
console.log('Original Array: ', arr)
console.log('Removed Elements: ', removed)
// arr is ['A', 'X', 'Y', 'Z']
// removed is ['B', 'C', 'D']
- At index 2, place 2 elements in place of 0 (zero) elements.
var arr = ['A', 'B', 'C', 'D'];
var removed = arr.splice(2, 0, 'X', 'Y');
console.log('Original Array: ', arr)
console.log('Removed Elements: ', removed)
// arr is ['A', 'B', 'X', 'Y', 'C', 'D']
// removed is []
- Delete all the elements after a particular index.
var arr = ['A', 'B', 'C', 'D', 'E', 'F'];
index = 3
var removed = arr.splice(index);
console.log('Original Array: ', arr)
console.log('Removed Elements: ', removed)
// arr is ['A', 'B', 'C']
// removed is ['D', 'E', 'F']
Note – The original array is updated using the splice() technique, as opposed to the slice() method, which leaves the original array unchanged.