SPLICE can DO a LOT!!!
We know that the splice function in JS is used to remove one or more elements starting from any index of a given array. It can also be used to add elements at a particular index.
Syntax of Splice
array.splice(start[, deleteCount[, item1[, item2[, …]]]])
In general, there are three parameters:
1. Start — states at which index the element to be added or removed.
2. deleteCount — states how many elements to be removed from the index specified.
for example: if it is 1, it deletes the specified index
3. items — (optional) states what is the element to be added in the array. Generally used to add an element to the existing array.
4. Returns — An array containing the deleted elements.
If only one element is removed, an array of one element is returned.
If no elements are removed, an empty array is returned.
The following examples can help illustrate the functionality of Splice better:
- let arr = [1,2,3,4]
arr.splice(0) // arr= 
As the start index is specified here as 0 but the delete count is not specified,
so it will directly remove all the elements from the array.
2. let arr = [1,2,3,4].
arr.splice(0,0) // arr = [1,2,3,4]
As the start is 0 and the deleteCount is 0. Hence, it returns the same array.
3. let arr = [1,2,3,4]
arr.splice(0,0,5) // arr = [1,2,3,4]
Here also there will not be any addition or deletion of the elements in the array which can be referred in eg-2
4. let arr = [1,2,3,4]
arr.splice(0,1) // arr = [2,3,4]
It deletes the element from index 1.
5. let arr = [1,2,3,4]
arr.splice(1,1,5) // [1,5,3,4]
It replaces 5 at index 1
6. let arr = [1,2,3,4]
arr.splice(1,2,5) // [1,5,4]
It replaces 1st and 2nd Index with one single element which is 5 here.
as 2 refers the delete count.
An interesting usage of splice can be to re-initialize an array in the following way:
For Re-initializing an array, we can also use arr.splice(0) which removes all the elements in the array.
arr.splice(0) // arr = .
I hope you now have a better understanding of the splice function. For a detailed info on the function, please check out the documentation below:
Thank you !!!