An array is a collection of values referenced by the array name. Once the array is initialized, we can easily add more elements or delete existing elements from an array. In this tutorial, you will learn to remove array elements by value in JavaSscript.
We can use the following JavaScript methods to remove an array element by its value.
indexOf()
– function is used to find array index number of given value. Return negavie number if the matching element not found.splice()
function is used to delete a particular index value and return updated array.
Remove Array Element in JavaScript
Use the indexOf()
and splice()
function to remove an array elements by its value. Let’s understand with an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <script type="text/JavaScript"> // Initialize array var arr = [5, 15, 110, 210, 65, 210]; console.log(arr); // Get the index of element var index = arr.indexOf(210); if (index > -1) { arr.splice(index, 1); // Remove array element } console.log(arr); </script> |
The second value in splice()
function tells to delete number of elements starting from index in array. See the below screenshot of the execution at playcode:
Did you notice that only the first occurrence of the matching element is deleted from the array? It’s because the indexOf() returns the single index number of the first matching value. To delete all the occurrences of the matching element use while loop. Let’s see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <script type="text/JavaScript"> // Initialize array var arr = [5, 15, 110, 210, 65, 210]; console.log(arr); var i = 0; while (i < arr.length) { if (arr[i] === 210) { arr.splice(i, 1); } else { ++i; } } console.log(arr); </script> |
Run this script again and see the results:
You will find that all the matching elements are deleted from the defined array.
Wrap Up
In this tutorial, you have learned about removing array elements by value in JavaScript.
If you like this tutorial, please share it with your social media handles. Also, provide your valuable suggestions in the comment box to improve this answer.
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.