Last Updated on April 19, 2024 by Roshan Parihar
To remove item from array by index in javascript, use the array.splice()
function and pass two arguments to perform this task.
You can also use the filter()
function to delete the element. Let’s find out with the examples given below.
Using splice() to Remove Item From Array in Javascript
If you want to remove item from array by index in javascript, you can use the array.splice()
function. It takes two arguments in which the first is the index position. The second is the numeber items to delete from array from the specified index.
Example 1
1 2 3 4 5 6 7 8 |
<script> function RemArrItem(){ var myArr= [9, 13, 21, 7, 3, 17]; //Array with 6 items var myIndexPos = 2; //index position is 2 myArr.splice(myIndexPos, 1); // remove 1 element at specified index document.getElementById("myNewArray").innerHTML = "<strong>The new array is: </strong>"+myArr; } </script> |
The above example contains six elements. The index position is 2 and we know that the array element starts from index zero(0). So, the 2nd index position item is 21 to remove from the array.
Delete Using filter() Function
In addition to the above example, you can also use the filter()
function. In this method, you have to first find the item present at the specified index. After that, you can delete the item with this function.
Example 2
1 2 3 4 5 6 7 8 9 10 11 |
<script> function DelArrbyIndex(){ var myArray= [9, 13, 21, 7, 3, 17]; var myIndexPos = 1; //index position is 2 var myItemToDelete = myArray[myIndexPos]; myArray = myArray.filter(function(item) { return item !== myItemToDelete; }); document.getElementById("myNewArray").innerHTML = "<strong>The new array is: </strong>"+myArray; } </script> |
The specified index position is 1 to remove the 2nd element from the array whic is 13.