Wednesday, September 25, 2024
Google search engine
HomeLanguagesJavascriptRemove empty elements from an array in JavaScript

Remove empty elements from an array in JavaScript

Many times there are empty elements in an array. In this article, we will see the methods to remove empty elements from the array. In order to remove empty elements from an array, here are some common approaches to removing empty elements from the array

Method 1: Using array.filter() method

This function creates a new array from a given array consisting of those elements from the provided array which satisfy conditions by the argument function.

array.filter( function(cValue, index, arr), tValue )

Example: This example is removing undefined, null, and empty elements from the array. 

Javascript




let array = ["GFG_1", "GFG_2", null, "GFG_3",
    "", "GFG_4", undefined, "GFG_5", , , , , ,
    "GFG_6", , 4, , 5, , 6, , , ,];
console.log("original array: " + array)
 
function myGeeks() {
    let filtered = array.filter(function (el) {
        return el != null;
    });
    console.log(filtered);
}
myGeeks()


Output

original array: GFG_1,GFG_2,,GFG_3,,GFG_4,,GFG_5,,,,,,GFG_6,,4,,5,,6,,,
[
  'GFG_1', 'GFG_2',
  'GFG_3', '',
  'GFG_4', 'GFG_5',
  'GFG_6', 4,
  5,       6
]


Method 2: Using array.reduce() method

In this method, we will use reduce() method. Use the reduce method to iterate over the array and check the falsey value and remove it from the array by using the if condition.

Example:

Javascript




let array = ["GFG_1", "GFG_2", null, "GFG_3",
    "", "GFG_4", undefined, "GFG_5",
    , , , , , "GFG_6", , 4, , 5, , 6, , , ,];
 
console.log("original array: " + array)
 
function myGeeks() {
    let filtered = array.reduce((acc, i) => i ? [...acc, i] : acc, []);
    console.log("new array: " + filtered)
}
myGeeks()


Output

original array: GFG_1,GFG_2,,GFG_3,,GFG_4,,GFG_5,,,,,,GFG_6,,4,,5,,6,,,
new array: GFG_1,GFG_2,GFG_3,GFG_4,GFG_5,GFG_6,4,5,6


Approach 3: Using for loop 

In this method, we will check element exists, and if it exists push it to the new array.

Example: In this example, we are using the above-explained approach.

Javascript




const arr = ["GFG_1", "GFG_2", null, "GFG_3",
    "", "GFG_4", undefined, "GFG_5", , , , , ,
    "GFG_6", , 4, , 5, , 6, , , ,];
 
// make a new array
// to hold non-empty values
const result = [];
 
for (let i = 0; i < arr.length; i++) {
    if (arr[i]) {
        result.push(arr[i]);
    }
}
 
console.log(result);


Output

[
  'GFG_1', 'GFG_2',
  'GFG_3', 'GFG_4',
  'GFG_5', 'GFG_6',
  4,       5,
  6
]


RELATED ARTICLES

Most Popular

Recent Comments