Skip to content
Related Articles
Open in App
Not now

Related Articles

Remove empty elements from an array in JavaScript

Improve Article
Save Article
  • Last Updated : 21 Dec, 2022
Improve Article
Save Article

Many times there are empty elements in an array. In this article, we will see the methods to remove empty elements from the array. In order to remove empty elements from an array, the filter() method is used. This method will return a new array with the elements that pass the condition of the callback function. 

Method 1: array.filter(): This function creates a new array from a given array consisting of those elements from the provided array which satisfy conditions by the argument function.

array.filter( function(cValue, index, arr), tValue )

Example: This example is removing undefined, null, and empty elements from the array. 

HTML




<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
   <h3>JavaScript | Remove empty
        elements from an array
   </h3>
    <p id="GFG_up" style="color:green;"></p>
    <button onclick="myGeeks()">
        Click here
    </button>
    <p id="GFG_down" style="color:green;"></p>
  
    <script>
        var array = ["GFG_1", "GFG_2", null, "GFG_3",
                    "", "GFG_4", undefined, "GFG_5",,,,,,
                    "GFG_6",, 4,, 5,, 6,,,,];
          
        var p_up = document.getElementById("GFG_up");
          
        p_up.innerHTML = array;
          
        function myGeeks() {
            var p_down = document.getElementById("GFG_down");
            var filtered = array.filter(function (el) {
                return el != null;
            });
            p_down.innerHTML = filtered;
        }
    </script>
</body>

Output:

 

Method 2: In this method, we will use reduce() method. Use the reduce method to iterate over the array and check the falsey value and remove it from the array by using the if condition.

Example:

HTML




<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <h3>JavaScript | Remove empty
        elements from an array</h3>
    <p id="GFG_up" style="color:green;"></p>
    <button onclick="myGeeks()">
        Click here
    </button>
    <p id="GFG_down" style="color:green;"></p>
  
    <script>
        var array = ["GFG_1", "GFG_2", null, "GFG_3",
                    "", "GFG_4", undefined, "GFG_5",
                    ,,,,, "GFG_6",, 4,, 5,, 6,,,,];
          
        var p_up = document.getElementById("GFG_up");
          
        p_up.innerHTML = array;
          
        function myGeeks() {
            var p_down = document.getElementById("GFG_down");
            var filtered = array.reduce((acc, i)=> i ? [...acc, i] : acc, []);
            p_down.innerHTML = filtered;
        }
    </script>
</body>

Output:

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!