How to Remove Element from an Array by Value in Javascript?

Sep 09, 2022 . Admin



Hello dev,

This tutorial will give you example of how to remove element from an array by value in javascript. you can see remove element from an array by value in javascript. I explained simply about how to remove item of an array by value in javascript. this example will help you javascript remove element of an array by value .

In this tutorial, we will explain to you to remove array elements by value in javascript. To remove an item from a given array by value, you need to get the index of that value by using the indexOf() function and then use the splice() function to remove the value from the array using its index.

In the second example we have another method to remove an element of an array by value, we can use the filter() function in JavaScript. The filter() function is used to filter values from a given array by applying a function defined inside the filter() function on each value of the array.

So, let's see bellow solution:

Example: 1
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Remove Element from an Array by Value in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Remove Element from an Array by Value in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            var arr1 = ['one', 'two', 'three'];
            var myIndex = arr1.indexOf('two');
            if (myIndex !== -1) {
                arr1.splice(myIndex, 1);
            }

            //give output to console...
            console.log(arr1);
        </script>
    </body>
</html>
Output:
['one', 'three']
Example: 2 index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Remove Element from an Array by Value in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Remove Element from an Array by Value in Javascript?-  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            var arr1 = ['one', 'two', 'three'];
            var newArray = arr1.filter(function(f) { return f !== 'two' });
            
            //give output to console...
            console.log(newArray);
        </script>
    </body>
</html>
Output:
['one', 'three']
I hope it will help you...
#Javascript