What is lodash.find?
The lodash.find npm package is a method from the Lodash library, which is a popular JavaScript utility library for manipulating and examining arrays, objects, and other data structures. The lodash.find function is used to search through an array or an object and return the first element that matches a specified condition.
What are lodash.find's main functionalities?
Find in Array
This code sample demonstrates how to use lodash.find to search through an array of objects and find the first object where the age is less than 40.
const _ = require('lodash');
const users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'pebbles', 'age': 1, 'active': true }
];
const result = _.find(users, function(o) { return o.age < 40; });
console.log(result);
Find with Shorthand Syntax
This example shows how to use lodash.find with an object shorthand syntax to find an element in the array that exactly matches the specified properties.
const _ = require('lodash');
const users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'pebbles', 'age': 1, 'active': true }
];
const result = _.find(users, { 'age': 1, 'active': true });
console.log(result);
Other packages similar to lodash.find
array.prototype.find
This is a polyfill for the Array.prototype.find method defined in ECMAScript 6. It offers similar functionality to lodash.find but is specifically a polyfill for the native JavaScript method, meaning it only works with arrays and not objects.
underscore
Underscore.js is a utility library similar to Lodash, and it includes a 'find' function. The syntax and usage are quite similar to lodash.find, but Lodash generally offers better performance and a more consistent API design.
lodash.find v4.6.0
The lodash method _.find
exported as a Node.js module.
Installation
Using npm:
$ {sudo -H} npm i -g npm
$ npm i --save lodash.find
In Node.js:
var find = require('lodash.find');
See the documentation or package source for more details.