You Can Filter Like That?
December 20, 2019
One of the joys of programming is stumbling across novel ways to solve common problems.
For example, take the totally banal task of filtering falsy values from an array.
I typically perform this task in one of two ways.
const array = [1, 2, undefined, 4] const filteredArray = array.filter(value => value)
Or, leveraging a utility like LoDash’s compact:
const array = [1, 2, undefined, 4] const filteredArray = _.compact(array)
While both approaches solve the problem, both feel inelegant. In the first example I dislike the redundancy of
This week, I came across a third approach I find much more appealing:
const array = [1, 2, undefined, 4] const filteredArray = array.filter(Boolean)
Native and not redundant!