Javascript Remove Empty Elements from Array

Javascript Remove Empty Elements from Array; In this tutorial, we will teach you how to remove the empty strings ” “, null values or undefined elements from an array in JavaScript.

Here we have added more then solutions example for remove empty elements, null or undefined elements from a JavaScript array.

Example 1: Using FIlter Method

Javascript array instance’s filter method is best solutiongs for remove empty elements from an array.

To remove all the empty, null or undefined elements from an array, we can write something below:

<script>
    const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
    const filtered = array.filter((el) => {
      return el !== null && el !== '' && typeof el !== 'undefined';
    });
    console.log(filtered);

//output [0, 1, 2, 3, 3, 4, 4, 5, 6]
</script>

Example 2: Remove All False Value from Array

If we want to remove all false values, we can just pass in the Boolean function to filter just like below:

<script>
    const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
    const filtered = array.filter(Boolean);
    console.log(filtered);

    //output  [1, 2, 3, 3, 4, 4, 5, 6]
</script>

Example 3: Filter with get Only Number

If we want to return an array with only the numbers left, we can write:

<script>
    const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
    const filtered = array.filter(Number);
    console.log(filtered);

    //output  [1, 2, 3, 3, 4, 4, 5, 6]
</script>

Example 4: Using Callback Method

And also get the same result since the callback’s return value will be cast to a boolean automatically.

<script>
    const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
    const filtered = array.filter(n => n);
    console.log(filtered);
    //output  [1, 2, 3, 3, 4, 4, 5, 6]
</script>

Example 5: Using Lodas compact Method

Lodash also has a filter method that does the same thing as the native filter method. Lodash compact method that’s specially made to remove falsy values from an array.

const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
const filtered = _.compact(array);
console.log(filtered);

Example 6: Remove Empty Elements from an Array using forEach

const arr = ['a', , 'b', , undefined, 0, 'c', null];

const results = [];

arr.forEach(element => {
  if (element !== null && element !== undefined) {
    results.push(element);
  }
});

console.log(results); //['a', 'b', 0, 'c']

I hope you enjoy with these Javascript Remove Empty Elements from Array example

Leave a Comment