Borislav Hadzhiev
Wed Oct 13 2021·2 min read
Photo by Becca Tapert
To remove all null values from an array:
filter()
method, passing it a function.null
.filter
method returns a new array, containing only the elements that
satisfy the condition.const arr = ['one', null, 'two', null, 'three', null]; const results = arr.filter(element => { return element !== null; }); console.log(results); // 👉️ ['one', 'two', 'three']
The function we passed to the Array.filter method gets called with each element in the array.
We explicitly check if each element is not equal to null
to only add non-null
elements to the new array.
filter
method does not change the contents of the original array. It returns a new array, containing only the elements that satisfy the condition.An alternative approach is to use the forEach
method.
To remove all null values from an array:
forEach()
method to iterate over the array.null
.const arr = ['one', null, 'two', null, 'three', null]; const results = []; arr.forEach(element => { if (element !== null) { results.push(element); } }); console.log(results); // 👉️ ['one', 'two', 'three']
The function we pass to the Array.forEach method gets invoked with each element in the array.
null
before pushing it into the results array.