Lodash's `filter()` Function
Given an array arr
, Lodash's filter()
function returns an array containing all the elements in arr
for which the function returned a truthy value.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
_.filter(arr, isEven); // [2, 4, 6, 8]
function isEven(v) { return v % 2 === 0; }
The function you pass to filter()
is called the predicate. If
the predicate returns a falsy value
(like null
, undefined
, 0
, or ''
), Lodash filters that value out.
const arr = [null, false, 0, 'hello'];
_.filter(arr, v => v); // ['hello']
On Arrays of Objects
The filter()
function has a couple convenient shorthands for
dealing with arrays of objects. If you pass a string predicate
instead of a function, Lodash will filter by whether that property
is truthy or falsy.
const arr = [
{},
{ hello: null },
{ hello: false },
{ hello: 0 },
{ hello: 'world' }
];
_.filter(arr, 'hello'); // [{ hello: 'world' }]
If your predicate is an object obj
, Lodash will filter objects that
match the given predicate.
In other words, Lodash will match objects that have the same value
as obj
for all properties in obj
.
const arr = [
{ firstName: 'Will', lastName: 'Riker', rank: 'Commander' },
{ firstName: 'Beverly', lastName: 'Crusher', rank: 'Commander' },
{ firstName: 'Wesley', lastName: 'Crusher', rank: 'Ensign' }
];
// ['Riker', 'Crusher']
_.filter(arr, { rank: 'Commander' }).map(v => v.lastName);
// ['Beverly', 'Wesley']
_.filter(arr, { lastName: 'Crusher' }).map(v => v.firstName);
// ['Beverly']
_.filter(arr, { lastName: 'Crusher', rank: 'Commander' }).map(v => v.firstName);
On Objects
The _.filter()
function can also accept an object as a parameter,
rather than an array. Calling _.filter(obj, fn)
behaves similarly
to _.filter(Object.values(obj), fn)
.
const obj = {
one: 1,
two: 2,
three: 3,
four: 4
};
_.filter(obj, v => v % 2 === 0); // [2, 4]