The JavaScript splice() method changes the elements of the array by replacing or removing the elements, in place.
Note: As compared to the
slice()method which does not change the original array,splice()method changes are reflected in the original array.
The syntax is as follows:
Removed: The array which stores all the removed elements that the splice() method returnsArray: The array on which splice() method is being appliedSplice: Function call to the methodIndex: Starting index for the splice() methodCount: Specifies the number of items in the array to replace/remove from the starting indexItems: Items that replace the array elements from the starting indexOptional Arguments:
Countanditemsarguments are optional in the function call.
Given below are some examples that show multiple ways to use the splice() method.
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']
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']
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 []
var arr = ['A', 'B', 'C', 'D', 'E', 'F'];index = 3var removed = arr.splice(index);console.log('Original Array: ', arr)console.log('Removed Elements: ', removed)// arr is ['A', 'B', 'C']// removed is ['D', 'E', 'F']
Free Resources