How to Remove Falsy Values from an Array
Last updated: December 1, 2022.
In JavaScript, there are six ‘falsy’ values:
// false
// undefined
// null
// NaN
// 0
// ''
Falsy values represent no value or the absence of value.
They are therefore the type of values you may want to remove from an array!
Falsy values can be filtered out of an array using the filter method:
const array = ["👨💻", null, "🐯", 0, '', "🍔"];
const res = array.filter(function(item) {
return Boolean(item);
});
console.log(res); // [ "👨💻", "🐯", "🍔" ]
In the above example, because Boolean(item)
returns false
if a value passed into it is falsy, it removes these values from the new array it creates.
Believe it or not, the above code can be abbreivated as followed:
const array = ["👨💻", null, "🐯", 0, '', "🍔"];
const res = array.filter(Boolean);
console.log(res); // [ "👨💻", "🐯", "🍔" ]
This works because Boolean
is a function and each array item is passed into it implicitly when it is placed inside alone inside the filter()
function.
Though this is pretty cool, it is often better to use to longer version in code because you cannot be certain others will understand the ‘Boolean trick’.
Remove only some falsy values
Sometimes, you may want to remove some falsy value from an array and not others. For example, in some circumstances, 0
and ""
(empty string) may be considered values worth keeping.
For this, use the logcal OR operator to add conditions that will return true if the desired falsy-to-be-truthy values are item
:
const array = ["👨💻", null, "🐯", 0, '', "🍔"];
const res = array.filter(function(item) {
return Boolean(item) || item === 0 || item === '';
});
console.log(res); // [ "👨💻", "🐯", 0, "", "🍔" ]
Related links
- Truthy and Falsy Values in JavaScript
- MDN Web Docs: Boolean Object