Skip to content

JS remove empty elements from an array | Example code

  • by

Use filter or Arrow function to Remove empty or whitespace or empty data from array in JavaScript.

JS remove empty elements from array example code

Let’s see HTML example code for it:-

Using Filter Function

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">

        var arr = ["I", "am", "", "still", "here", "", "man"];
        
        console.log(arr.filter(Boolean));

    </script>
</head>
<body>

</body>

</html>

Output:

JS remove empty elements from an array

Using Arrow function

<script type="text/javascript">

        var arr = ["I", "am", "", "still", "here", "", "man"];
        
        console.log(arr = arr.filter(v=>v!=''));

    </script>

You could use the filter one more way like:

arr = arr.filter(item => item);

Example

<script type="text/javascript">

        let arr = ['One', 'Two', '', 'Four', '', ''];
        arr = arr.filter(item => item);
        console.log(arr);

</script>

Output:

Array(3) [ “One”, “Two”, “Four” ]

Because an empty string evaluates to boolean false. It works with all falsy values like 0, false, null, undefined, '', etc.

Note: If you want to keep some values like the number 0 (zero) you could use item !== undefined. This filters only undefined values. Keep in mind to trim your string or check with regex to ensure empty strings without whitespaces.

Source: Stackoverflow.com

Do comment if you have any doubts or questions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading