How to Remove Element of an Array if Exists in Javascript?

Sep 10, 2022 . Admin



Hello dev,

I am going to explain you example of how to remove element of an array if exists in javascript. you will learn javascript remove element of array if exists. We will use how to delete a value from array if exists. if you have question about remove from array if exists javascript code example then I will give simple example with solution.

In this example, I am going to explain to you to remove the element of an array if exists. You can use the indexOf() method to check whether a given value or element exists in an array or not if exists then you have to use the splice() method to remove the element.

in the second example we have the second condition is value exists then you add a new element to the array.You can use the indexOf() method to check whether a given value or element exists in an array or not.

So, let's see bellow solution:

Example: 1
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Remove Element of an Array if Exists in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Remove Element of an Array if Exists in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

            // Check if a value exists in the fruits array
            if(fruits.indexOf("Mango") !== -1){
                fruits.splice(fruits.indexOf("Mango"), 1);
            } else{
                alert("Value does not exists!");
            }
            console.log(fruits);
        </script>
    </body>
</html>
Output:
['Apple', 'Banana', 'Orange', 'Papaya']
Example: 2 index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Remove Element of an Array if Exists in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Remove Element of an Array if Exists in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            var fruits = ["Apple", "Banana","Orange", "Papaya"];

            // Check if a value exists in the fruits array
            if(fruits.indexOf("mango") !== -1){
                fruits.splice(fruits.indexOf("mango"), 1);
            } else{
                fruits.push("mango");
            }
            console.log(fruits);
        </script>
    </body>
</html>
Output:
['Apple', 'Banana', 'Orange', 'Papaya', 'mango']
I hope it will help you...
#Javascript