How to remove empty values from an array
Short answer
filter(Boolean) keeps only truthy values. It removes null, undefined, empty strings, 0, false and NaN:
const values = ['a', '', null, 'b', undefined, 0, 'c'];
console.log(values.filter(Boolean));Output:
[
"a",
"b",
"c"
]Keep zeros
If 0 and false are real data, remove only null, undefined and empty strings:
const values = [0, '', null, 5, undefined, false];
const clean = values.filter((value) => value !== null && value !== undefined && value !== '');
console.log(JSON.stringify(clean));Output:
[0,5,false]Strings of spaces
Trim strings first if spaces should count as empty:
const tags = ['js', ' ', 'css', ''];
console.log(tags.map((tag) => tag.trim()).filter(Boolean).join(', '));Output:
js, cssCommon mistake
filter(Boolean) also removes zeros, which is often a bug in lists of numbers:
console.log([3, 0, 7].filter(Boolean).join(', '));Output:
3, 7Functions used in this recipe
- Array.prototype.filter — Creates a new array from the elements that pass a test.
- Boolean() — Converts a value to true or false.