Last Updated on April 19, 2024 by Roshan Parihar
To remove an item from an array in javascript, use the splice()
function with indexOf()
. It first finds the index position and then deletes the item.
You can also choose to use the filter()
function to delete the given element of an array in javascript. Let’s see with the examples given below.
Using indexOf() and splice() to Remove Item From Array in Javascript
If you want to remove an item from an array in javascript, you can use this method which first finds the index position of the item. After that, it uses the array.splice()
function to remove th item.
Example 1
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<script> function RemArrItem(){ var myArr= [9, 13, 21, 7, 3, 17]; var ItemtoRemove = 7; var ArrIndex = myArr.indexOf(ItemtoRemove); if(ArrIndex > -1){ myArr.splice(ArrIndex, 1); } document.getElementById("myNewArray").innerHTML = "<strong>The new array is: </strong>"+myArr; } </script> <button onclick="RemArrItem()">Remove Array Element</button> <p id="myNewArray"></p> |
Output
The given item to remove from the array is 7. When you click the button given above, you will get an array printed in the output with the removed specified array item.
Delete Array Items Using filter()
Function in Javascript
The filter()
function filters out the specified item from the array. It does not require any other function to use and deletes the item from an array.
Example 2
1 2 3 4 5 6 7 8 9 10 11 12 |
<script> function RemArrItem(){ var myArr= [9, 13, 21, 7, 3, 17]; var ItemtoRemove = 21; myArr = myArr.filter(function(item) { return item !== ItemtoRemove; }); document.getElementById("myNewArray").innerHTML = "<strong>The new array is: </strong>"+myArr; } </script> <button onclick="RemArrItem()">Remove Array Element</button> <p id="myNewArray"></p> |
Output
The specified element to remove from the given array is 21. Click the button given above to get the new array without the specified element removed from the array.
With For Loop and splice() Function
In addition to the above methods, you can also use the for
loop with splice()
function to remove array items in javascript. It also requires matching the item in each loop using the if condition.
Example 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script> function RemArrItem(){ var myArr= [9, 13, 21, 7, 3, 17]; var ItemtoRemove = 13; for(i = 0;i < myArr.length; i++){ if(myArr[i] == ItemtoRemove){ myArr.splice(i, 1); } } document.getElementById("myNewArray").innerHTML = "<strong>The new array is: </strong>"+myArr; } </script> <button onclick="RemArrItem()">Remove Array Element</button> <p id="myNewArray"></p> |
Output
The given element is 13 that you have to delete from the given array of elements. Click the button given above to get the specified element removed from the given array. You can check the output gives the new array without the element 13.
You May Also Like to Read