How to Remove Null Values from an Array in Javascript?

Sep 22, 2022 . Admin



Hello dev,

This article is focused on how to remove null values from an array in javascript. In this article, we will implement a how to remove null element from an array in javascript. I would like to show you how to remove null items of array in javascript. We will use javascript remove null values in array.

In this tutorial, I will explain to you how to remove null values from an array in javascript. To remove all null values from an array Use the Array.filter() method to iterate over the array. The filter() method returns a new array containing only the elements that satisfy the condition.

So, let's see bellow solution:

Example: 1
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Remove Null Values from an Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Remove Null Values from an Array in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            const colors = ['Red', null, 'Green', null, 'Yellow', null];
            const results = colors.filter(element => {
              return element !== null;
            });

            //Give output to console...
            console.log(results);
        </script>
    </body>
</html>
Output:
['Red', 'Green', 'Yellow']
I hope it will help you...
#Javascript