Using Lodash's find() Function
Lodash's find()
function returns
the first element of a collection that matches the given predicate
.
const arr = [1, 2, 3, 4, 5];
// `find()` executes `predicate` for every element in the array until
// `predicate` returns true.
const predicate = v => v > 3;
_.find(arr, predicate); // 4
find()
is different from Lodash's filter()
function because filter()
returns all elements that match a condition, whereas find()
returns the first element that matches a condition.
If find()
doesn't find an element, it returns undefined
.
const arr = [1, 2, 3, 4, 5];
_.find(arr, v => v > 5); // undefined
The find()
function operates on a collection, not an array, which means
you can use it on objects too.
const obj = { key1: 1, key2: 2, key3: 3 };
_.find(obj, v => v > 2); // 3
Alternative Syntaxes
find()
supports two alernative syntaxes. If you pass an object as the predicate,
the find()
function will create a predicate function using the matches()
function which performs a partial deep comparison. That means Lodash will find the first object in the collection that has the given properties.
const characters = [
{ firstName: 'Jean-Luc', lastName: 'Picard', rank: 'Captain', age: 59 },
{ firstName: 'Will', lastName: 'Riker', rank: 'Commander', age: 29 },
{ firstName: 'Geordi', lastName: 'La Forge', rank: 'Lieutenant', age: 29 }
];
_.find(characters, { rank: 'Commander', age: 29 }).lastName; // 'Riker'
If you pass a string str
as the predicate, the find()
function will return the first object in the array that has a truthy property str
.
const characters = [
{ name: 'Doctor Pulaski' },
{ name: 'Tasha Yar', active: false },
{ name: 'Wesley Crusher', active: null },
{ name: 'Jean-Luc Picard', active: true }
];
// Find the first character with a truthy `active` property
_.find(characters, 'active').name; // 'Jean-Luc Picard'