One of the common operations with an array is removing the item. We will learn about how to remove an item from an array using
But before that, let me introduce you
splice() function can add or remove an item from an array. Thus changing the original array.
Splice() function Syntax
Splice() function will start from here. Keep in mind, an array index start from 0.
Also, if starting_index is greater than the length of the array. Then
If it is negative, in this case, it will begin that many elements from the end of the array.
For example, with origin -1, meaning -n is the index of the nth last element. Thus it is equal to the index of
This is the count of elements in the array to remove from starting_index.
Here, you can add the list of items in the array.
Splice() Return Value
splice() function will return an array containing the deleted items.
Below are the examples demonstrating the
Removing an item from index 1
Removing 2 items from index 1
Remove all items from index 1
Remove and insert an item on index 1 when count is 0 (zero)
Note that, we passed 0 in count parameter. That means, no item will remove from the array. It will insert new item on the same index position of 1.
Remove and insert an item on index 1 when count is 1 (zero)
Let’s repeat the above example with count 1 in the second parameter of
splice() function. As a result, it will remove and then insert an item in the same position. In other words, it is replacing the item.