How to use array.filter() method In Javascript
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.
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 ]
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.
Below are the approaches used to Remove empty elements from an array in JavaScript:
Table of Content
- Using array.filter() method
- Using array.reduce() method
- Using for loop
- Using JavaScript Array flat() Method