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.

Advertisement

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:

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:

Remove Elements in Array by Value in JavaScript
Remove one array element by value.

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:

Remove all matching array elements in array by value

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.

Share.

6 Comments

  1. 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);
    }

  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.

Leave A Reply

Exit mobile version