How to usefor loop in Javascript
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.
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 ]
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