To remove empty elements from an array, you must follow the following steps:
null
, undefined
, ""
(empty string), and NaN
.let shoppingList = ['Apples', 'Milk', null, 'Bread', undefined, "Biscuits", NaN, ""]; let result = shoppingList.filter(element => { if(element !== null && element !== undefined && !Number.isNaN(element) && element !== ""){ return true; } }); console.log(result); //["Apples", "Milk", "Bread", "Biscuits"]
The callback function of the filter() method is called for each array element. You specify the condition using the logical && operator inside the callback function so that you can remove empty elements from the array.
Note: The filter() method does not modify the original array. Instead, it returns a new array whose elements satisfy the condition.
There is an alternative way if you don't want to use the filter() method, which is to use the forEach() method.
To remove empty elements from an array using the forEach() method, you must follow the following steps:
let result = []; let shoppingList = ['Apples', 'Milk', null, 'Bread', undefined, "Biscuits", NaN, ""]; shoppingList.forEach(element => { if(element !== null && element !== undefined && !Number.isNaN(element) && element !== ""){ result.push(element); } }); console.log(result); //["Apples", "Milk", "Bread", "Biscuits"]