Skip to content
Related Articles

Related Articles

Improve Article

Lodash | _.find() Method

  • Last Updated : 25 May, 2021

The _.find() method accessing each value of the collection and returns the first element that passes a truth test for the predicate or undefined if no value passes the test. The function returns as soon as it finds the match. So it actually searches for elements according to the predicate.
Syntax: 
 

_.find(collection, predicate, fromIndex)

Parameters: This method accept three parameters as mentioned above and described below: 
 

  • collection: This parameter holds the array or object collection that need to inspect.
  • predicate: This parameter holds the function invoked the iteration.
  • fromIndex: This parameter holds the index from which you want to start searching (optional). If you don’t pass this parameter then it start searching from the beginning.

Return Value: It returns the matched element or undefined if nothing match.
Example 1: Tn this example, we will try to find the first number whose square is more than 100. 
 

javascript




const _ = require('lodash');
 
let x = [2, 5, 7, 10, 13, 15];
 
let result = _.find(x, function(n) {
    if (n * n > 100) {
        return true;
    }
});
 
console.log(result);

Here, const _ = require(‘lodash’) is used to import the lodash library into the file.
Output: 
 



13

Example 2: In this example, we will find the first number in the list which is greater than 10 but start searching from index 2. 
 

javascript




const _ = require('lodash');
 
let x = [-1, 29, 7, 10, 13, 15];
 
let result = _.find(x, function(n) {
    if (n > 10) {
        return true;
    }
}, 2);
 
console.log(result);

Output: 
 

13

Example 3: In this example, we will search for the first student (object) in the list who has more score than 90. 
 

javascript




const _ = require('lodash');
 
let x = [
    {'name': 'Akhil', marks:'78'},
    {'name': 'Akhil', marks:'98'},
    {'name': 'Akhil', marks:'97'}
];
 
let result = _.find(x, function(obj) {
    if (obj.marks > 90) {
        return true;
    }
});
 
console.log(result);

Output: 
 

{ name: 'Akhil', marks: '98' }

Example 4: When none element return true on predicate. 
 

javascript




const _ = require('lodash');
 
let x = [1, 2, 7, 10, 13, 15];
 
let result = _.find(x, function(n) {
    if (n < 0) {
        return true;
    }
});
 
console.log(result);

Output: 
 

undefined

Note: This will not work in normal JavaScript because it requires the library lodash to be installed.
Reference: https://lodash.com/docs/4.17.15#find
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :