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.
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.
splice() function to remove an array elements by its value. Let’s understand with an example:
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:
Run this script again and see the results:
You will find that all the matching elements are deleted from the defined array.
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.