How do you remove falsy values from an array with filter in JavaScript?
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).
Verify This Answer
Cross-check this information using these trusted sources:
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
