In earlier post, we have seen how to create array in JavaScript and various others built-in array methods. now we learn how to remove an item from JavaScript array.
There are different ways we can remove item from an array in JavaScript, let’s consider following different scenario.
First let's create an array , so we can experiment how differently we can remove items from array.
var teamA = new Array(); teamA.push("Sachin"); teamA.push("Saurav"); teamA.push("Dhoni"); teamA.push("Dravid"); teamA.push("Prasad"); teamA.push("Harbhajan"); teamA.push("Irfan"); teamA.push("Rohit"); teamA.push("Lara");
There are different built-in methods to remove an item from array.
Shift method will remove the first item from the array.
teamA.shift(); console.log(teamA.toString());
Now if you see the below result, the first name “Sachin” has been removed from the list.
Saurav,Dhoni,Dravid,Prasad,Harbhajan,Irfan,Rohit,Lara
Pop method will remove the last item from the array.
teamA.pop(); console.log(teamA.toString());
Notice, in below result, the last name “Lara” has been removed from the list.
Sachin,Saurav,Dhoni,Dravid,Prasad,Harbhajan,Irfan,Rohit
We can use splice method in different ways.
Following splice method will remove all the items from array-index position 2, means only 0 and 1 will remain
teamA.splice(2) console.log(teamA.toString());
Only first two name will remain, all are removed
Sachin,Saurav
Now, let’s call splice method differently, if we call teamA.splice(2,1)
, that will remove 1 item from second (2) index position.
teamA.splice(2,1) console.log(teamA.toString());
See, the name “Dhoni” has been removed, which was in second index position, all are remaining.
Sachin,Saurav,Dravid,Prasad,Harbhajan,Irfan,Rohit,Lara
Means teamA.splice(indexPosition, NoOfElements)
,
if we don’t specify the number of elements to be removed, all elements will be removed after that index position.
We can use delete keyword to delete one element from array using the index number, that will delete the value and make the position empty.
delete teamA[4]; console.log(teamA.toString());
This will delete the item from 4th index position, means "Prasad" will be deleted, but there will be empty space.
Sachin,Saurav,Dhoni,Dravid,,Harbhajan,Irfan,Rohit,Lara
Notice, the specified index value is deleted, but there is a space , ,
Now, so far we have seen how to remove an item from array in javascript, where we know exactly which item to be deleted, and there is no where condition or multiple condition, that means delete call was straight and simple.
In real-time business scenario, sometimes we need to remove an item from array depending on some other input values, in such situation we need to write custom method, where after satisfying the condition we may call any of above methods to remove the item from array.
You may be interested in following posts: