JS remove empty elements from an array | Example code

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.