The best way to remove an element from an array based on the value in JavaScript is to find index number of that value in an array using indexOf() function and then delete particular index value using the splice() function. For example use following code.
Sample JavaScript Code
<script type="text/JavaScript"> var arr = [5, 15, 110, 210, 550]; var index = arr.indexOf(210); if (index > -1) { arr.splice(index, 1); } </script>
Explanation:
- Line 1 – We have initialized an array named arr with few static values.
- Line 2 – Now we use
indexOf() function to find the index number of given value in array. If given value found in array , it will return index number, else it will remove values less than 0. - Line 3 – First check if return index number is >=0, then only delete the value from that index from array using
splice() function.
6 Comments
arr = arr.filter(x=>x!=2)
Thank You Very Much
Thanks for this code, this code helped me, Very good!
This is a great example of how to use Splice(). Thank you for sharing.
Delete all occurrences of a specified value from an array:
var arr = [100,2,500,3,2,240,35,2];
removedIndx = arr.indexOf(2);
while(removedIndx > -1) {
arr.splice(removedIndx,1);
removedIndx = arr.indexOf(2);
}
For practical purposes, you probably want that in a while loop. A “delete by value” function should logically delete all occurrences of that value.