Open In App

Remove Empty Elements from an Array in JavaScript

Last Updated : 11 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Share
2 Likes
Like
Report

Here are different approaches to remove empty elements from an Array in JavaScript.

1. Using array.filter() Method

The array filter() method is used to create a new array from a given array consisting of elements that satisfy given conditions.

array.filter( callback( element, index, arr ), thisValue )

Output
Updated Array:  [ 10, 20, 30, 40, 50 ]

2. Using array reduce() Method

The array reduce() method is used to iterate over the array and on each iteration check the falsey value and remove it from the array by using the if condition.

Syntax

array.reduce( function(total, currentValue, currentIndex, arr), initialValue )

Output
Updated Array:  [ 10, 20, 30, 40, 50 ]

3. Using Array flat() Method

The Array flat() Method was introduced in ES2019. It is used to flatten an array, to reduce the nesting of an array. The flat() method is heavily used in the functional programming paradigm of JavaScript.

Syntax

arr.flat()

Output
Updated Array:  [ 10, null, 20, undefined, '', 30, 40, 50 ]

Note: This method only remove the empty elements not other values like empty string, null, and undefined.

4. Brute Force Approach

The splice() method can be used to directly modify an array by removing or replacing existing elements. Iterate through the array in reverse order and use splice() to remove empty elements (like undefined, null, or empty strings) in place.


Output
Updated Array:  [ 10, 20, 30, 40, 50 ]

5. Using forEach() with push() Methods

You can use forEach() method to iterate through the array, pushing only non-empty elements into a new array. This method provides a more manual approach where you have full control over what to include or exclude.

Syntax

array.forEach(callback(element, index, arr), thisValue);

Output
Updated Array:  [ 10, 20, 30, 40, 50 ]

Similar Reads