Use filter(Boolean). Boolean is a function that returns the truthiness of a value. Passing it to filter removes all falsy values (0, '', null, undefined, false, NaN).
filter in JavaScript: Examples and Use Cases
How do you remove falsy values from an array with filter in JavaScript?
The answer
More FAQs in filter in JavaScript: Examples and Use Cases
It calls a callback on each element and returns a new array with only the elements where the callback returned truthy. The original array is not mutated.
filter returns all matching elements as an array (possibly empty). find returns the first matching element (or undefined). Use filter when you want all matches; use find when you want one.
Use arr.filter((n, i, arr) => arr.indexOf(n) === i). This keeps only the first occurrence of each value. Or use [...new Set(arr)] which is simpler and faster.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.