Knowledge Tile focused on Lodash's find method - comprehensive documentation for collection searching with multiple predicate formats and performance optimizations.
npx @tessl/cli install tessl/npm-lodash--find@4.6.00
# Lodash Find
1
2
The `find` method from Lodash iterates over elements of a collection, returning the first element that a predicate function returns truthy for. It supports multiple predicate formats including functions, objects, arrays, and strings, providing flexible and powerful search capabilities for both arrays and objects.
3
4
> **Note**: This Knowledge Tile provides comprehensive documentation specifically for Lodash's `find` method. It is a focused, single-method tile rather than complete Lodash package documentation.
5
6
## Package Information
7
8
- **Package Name**: lodash
9
- **Package Type**: npm
10
- **Language**: JavaScript
11
- **Installation**: `npm install lodash`
12
13
## Core Imports
14
15
```javascript
16
import _ from "lodash";
17
// Use as _.find()
18
```
19
20
For CommonJS:
21
22
```javascript
23
const _ = require("lodash");
24
// Use as _.find()
25
```
26
27
With modern bundlers and tree-shaking:
28
29
```javascript
30
// Option 1: Use lodash-es for better tree-shaking
31
import { find } from "lodash-es";
32
33
// Option 2: Direct import from specific module (if available)
34
import find from "lodash/find";
35
36
// Note: Tree-shaking with lodash requires lodash-es or modular imports
37
```
38
39
## Basic Usage
40
41
```javascript
42
import _ from "lodash";
43
44
const users = [
45
{ user: 'barney', age: 36, active: true },
46
{ user: 'fred', age: 40, active: false },
47
{ user: 'pebbles', age: 1, active: true }
48
];
49
50
// Find using a function predicate
51
const youngUser = _.find(users, function(o) { return o.age < 40; });
52
// => { user: 'barney', age: 36, active: true }
53
54
// Find using object properties
55
const child = _.find(users, { age: 1, active: true });
56
// => { user: 'pebbles', age: 1, active: true }
57
58
// Find using property-value pair
59
const inactiveUser = _.find(users, ['active', false]);
60
// => { user: 'fred', age: 40, active: false }
61
62
// Find using property name
63
const activeUser = _.find(users, 'active');
64
// => { user: 'barney', age: 36, active: true }
65
```
66
67
## Architecture
68
69
The `find` method is part of Lodash's collection iteration system with several key architectural features:
70
71
- **Shortcut Fusion**: When used in method chains, `find` can terminate early without processing the entire collection, providing significant performance benefits
72
- **Lazy Evaluation**: In chained operations, transformations are applied on-demand as `find` iterates, not to the entire collection upfront
73
- **Iteratee Integration**: Uses Lodash's internal `_.iteratee` system for predicate normalization, allowing flexible predicate formats
74
- **Optimized Implementation**: Different code paths for arrays vs objects to maximize performance
75
76
## Capabilities
77
78
### Find Function
79
80
Iterates over elements of collection, returning the first element predicate returns truthy for.
81
82
```javascript { .api }
83
/**
84
* Iterates over elements of collection, returning the first element
85
* predicate returns truthy for. The predicate is invoked with three arguments:
86
* (value, index|key, collection).
87
*
88
* @param {Array|Object} collection - The collection to search
89
* @param {Function|Object|Array|string} [predicate=_.identity] - The function invoked per iteration.
90
* - Function: Receives (value, index|key, collection) and returns boolean
91
* - Object: Uses _.matches for deep property matching
92
* - Array: Uses _.matchesProperty for [property, value] pair matching
93
* - String: Uses _.property for truthy property checking
94
* @returns {*} Returns the matched element, else undefined
95
*/
96
function find(collection, predicate);
97
```
98
99
**Parameters:**
100
101
- `collection` (Array|Object): The collection to search
102
- `predicate` (Function|Object|Array|string) [optional, defaults to _.identity]: The function invoked per iteration
103
104
**Predicate Format Options:**
105
106
1. **Function**: `function(value, index|key, collection) => boolean`
107
- Receives three arguments: the current value, its index/key, and the collection
108
- Returns true for elements that should be selected
109
110
2. **Object**: `{ property: value, ... }`
111
- Matches elements that have all specified properties with matching values
112
- Uses strict equality (`===`) for value comparison
113
114
3. **Array**: `[property, value]`
115
- Matches elements where the specified property equals the given value
116
- Shorthand for property-value pair matching
117
118
4. **String**: `"property"`
119
- Matches elements where the specified property is truthy
120
- Equivalent to `function(o) { return !!o[property]; }`
121
122
**Returns:**
123
- `*`: The first matched element, or `undefined` if no match is found
124
125
**Behavior:**
126
- Stops iteration immediately when the first match is found
127
- Works with both arrays and objects
128
- For arrays, iterates by index in ascending order
129
- For objects, iterates over own enumerable properties
130
- Returns `undefined` if no element matches the predicate
131
- Uses Lodash's internal iteratee system for predicate normalization
132
133
**Usage Examples:**
134
135
```javascript
136
import _ from "lodash";
137
138
// Array of objects
139
const employees = [
140
{ name: 'Alice', department: 'Engineering', salary: 75000 },
141
{ name: 'Bob', department: 'Sales', salary: 60000 },
142
{ name: 'Charlie', department: 'Engineering', salary: 80000 }
143
];
144
145
// Function predicate with custom logic
146
const highEarner = _.find(employees, function(employee) {
147
return employee.salary > 70000;
148
});
149
// => { name: 'Alice', department: 'Engineering', salary: 75000 }
150
151
// Object predicate for exact match
152
const salesPerson = _.find(employees, { department: 'Sales' });
153
// => { name: 'Bob', department: 'Sales', salary: 60000 }
154
155
// Array predicate for property-value pair
156
const charlie = _.find(employees, ['name', 'Charlie']);
157
// => { name: 'Charlie', department: 'Engineering', salary: 80000 }
158
159
// String predicate for truthy property
160
const products = [
161
{ name: 'Laptop', featured: false },
162
{ name: 'Phone', featured: true },
163
{ name: 'Tablet' }
164
];
165
166
const featuredProduct = _.find(products, 'featured');
167
// => { name: 'Phone', featured: true }
168
169
// Working with plain arrays
170
const numbers = [1, 2, 3, 4, 5];
171
const evenNumber = _.find(numbers, function(n) { return n % 2 === 0; });
172
// => 2
173
174
// Working with objects (not arrays)
175
const userRoles = {
176
admin: { permissions: ['read', 'write', 'delete'] },
177
editor: { permissions: ['read', 'write'] },
178
viewer: { permissions: ['read'] }
179
};
180
181
const writeUser = _.find(userRoles, function(role) {
182
return role.permissions.includes('write');
183
});
184
// => { permissions: ['read', 'write', 'delete'] }
185
186
// No match found
187
const notFound = _.find(employees, { department: 'Marketing' });
188
// => undefined
189
190
// Chaining with lazy evaluation and shortcut fusion
191
const largeDataset = _.range(1, 10000);
192
const result = _(largeDataset)
193
.map(n => n * n) // Only applied to elements until first match
194
.filter(n => n > 100) // Only applied to elements until first match
195
.find(n => n % 7 === 0); // Stops at first match: 121 (11²)
196
// => 121
197
// Note: Only processes ~11 elements instead of all 10,000
198
```
199
200
**Performance Characteristics:**
201
- Time complexity: O(n) in worst case, where n is the collection size
202
- Space complexity: O(1)
203
- Stops at first match for optimal performance
204
- Array iteration is index-based for better performance than object iteration
205
- **Shortcut Fusion**: In method chains, only processes elements until first match, potentially avoiding expensive transformations on the rest of the collection
206
207
**Integration with Lodash Ecosystem:**
208
- Uses `_.iteratee` internally for predicate processing, enabling the flexible predicate formats
209
- Supports lazy evaluation when used in `_(collection).chain()` sequences
210
- Optimizes performance through early termination in chained operations
211
212
**Error Handling:**
213
- Does not throw errors for invalid predicates
214
- Returns `undefined` for non-collection inputs
215
- Gracefully handles null/undefined collection parameters