To add or remove values from any position of an array in JavaScript, we can use splice()
function. Here is the code –
var arr = ["item 1", "item 2", "item 3", "item 4"]; arr.splice(index where item to be added or removed, number of items to remove);
This function has 2 required parameters and all other are optional. These parameters are –
-
Index
– (Required) The first parameter is the index where you want to add new items or remove items from that index. -
Number of items
– (Required) Second parameter is the number of items you want to remove from givenindex
. -
items
– (Optional) These are comma separated list of items which you want to add in your array at theindex
.
You may also like –
Use cases and examples of splice()
Suppose the given array is –
var arr = ["item 1", "item 2", "item 3", "item 4"];
Example 1 – You want to remove 3rd item
3rd item means, array index 2, because indexes starts from 0. Use splice()
like this –
arr.splice(2, 1);
First parameter is index
so we used 2 and second parameter is number of items
so we used 1. Our final array will become –
["item 1", "item 2", "item 4"];
Example 2 – You want to add 2 items at 3rd position
It means you want to add 2 items (let’s say – item 5 and item 6) at 2nd index of array. You should use the function like this –
arr.splice(2, 0, "item 5", "item 6");
You can see that we have used 0 as second parameter. This is because we do not want to remove any item. We just want to add two new items at index 2.
Final array will appear like this –
["item 1", "item 2", "item 5", "item 6", "item 3", "item 4"];
Example 3 – Removing 2nd and 3rd item and adding 4 items at their place
Removing 2nd and 3rd item = removing 2 items from 1st index.
Let’s say we want to add these 4 items – new item 1, new item 2, new item 3, new item 4.
So, final array should look like this –
["item 1", "new item 1", "new item 2", "new item 3", "new item 4", "item 4"];
Use splice()
in this way –
arr.splice(1, 2, "new item 1", "new item 2", "new item 3", "new item 4");
Note:
splice()
can only remove consecutive items. Like you can’t remove 2nd and 4th item. But you can remove 2nd, 3rd and 4th item.This is because function takes initial index and number of items to remove.