Skip to content

How to Remove JavaScript Array Element by Value

How to Remove Array Element by Value in JavaScript. This tutorial will help you to remove JavaScript array element by value

On this page

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:

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 Elements in Array by Value - JavaScript
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.

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

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

Your email address will not be published. Required fields are marked *


Back to top