How to Remove Empty Values from an Array in Javascript?

Sep 15, 2022 . Admin



Hello dev,

This tutorial shows you how to remove empty values from an array in javascript. I would like to show you how to remove empty element from an array in javascript. I would like to show you how to remove empty element of array in javascript. This post will give you simple example of remove empty element from an array in javascript example.

In this tutorial, I am going to explain you to remove empty elements from an array.To remove empty, null, or undefined elements from an array, we can use the filter() array method and pass a function to the method which returns the element currently getting looped.

In the second example we have another way to remove empty element in array. this method is filter() with for loop.to use a for loop and check if the element evaluates to true inside the loop and if it does add that element to the new array this

So, let's see bellow solution:

Example: 1
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Remove Empty Values from an Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Remove Empty Values from an Array in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            const arr = [1, , , , 2, 3, 4, 56, "text", null, undefined, 67, ,];

            // use filter() array method...
            const newArr = arr.filter((a) => a);

            //Give output to console...
            console.log(newArr);
        </script>
    </body>
</html>
Output:
[1, 2, 3, 4, 56, 'text', 67]
Example: 2 index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Remove Empty Values from an Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Remove Empty Values from an Array in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            const arr = [1, , , , 2, 3, 4, 56, "text", null, undefined, 67, ,];

            // make a new array...
            const newArr = [];

            // use for loop...
            for (let i = 0; i < arr.length; i++){
                if (arr[i]) {
                    newArr.push(arr[i]);
                }
            }

            //Give output to console...
            console.log(newArr);
        </script>
    </body>
</html>
Output:
[1, 2, 3, 4, 56, 'text', 67]
I hope it will help you...
#Javascript