To remove null values from an array, you must follow the following steps:
filter()
method, compare each array value to null
.null
, then return false
. Here, false
means that array element won't become part of the new array.let shoppingList = ['Apples', 'Milk', null, 'Bread', null, "Biscuits", null]; let result = shoppingList.filter(element => { if(element !== null){ return true; }else{ return false; } }); console.log(result); //["Apples", "Milk", "Bread", "Biscuits"]
Note: It is important to note that the filter()
method does not modify the original array. Instead, it returns a new array whose elements satisfy the condition.
If you don't want to use the filter() method, then you can use the forEach() method.
To remove null values from an array using the forEach() method, you must follow the following steps:
forEach()
method on the array from which you want to remove null values.forEach()
method, check if the current processing element is not equal to null
. If the condition is satisfied, push that array element into the empty array created in step 1.let result = []; let shoppingList = ['Apples', 'Milk', null, 'Bread', null, "Biscuits", null]; shoppingList.forEach(element => { if(element !== null){ result.push(element) } }); console.log(result); //["Apples", "Milk", "Bread", "Biscuits"]