How to use array.reduce() method In Javascript
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: In this example we are using array.reduce() method.
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
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