How to usea custom function in Javascript
In this approach, we can define a custom function that iterates through the array and removes empty elements based on specific conditions, such as checking for undefined, null, or empty strings.
Example:
function removeEmptyElements(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== undefined && arr[i] !== null && arr[i] !== "") {
result.push(arr[i]);
}
}
return result;
}
let arr = [1, 2, "", 3, undefined, 4, null, 5];
let filteredArr = removeEmptyElements(arr);
console.log(filteredArr); // Output: [1, 2, 3, 4, 5]
Output
[ 1, 2, 3, 4, 5 ]
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