How to find items in an array based on certain criteria in Lodash
Overview
In Lodash, we use the _.filter() method to find items in an array based on specific criteria. This method iterates over all the array elements and returns those elements for which the predicates return a truthy value.
Syntax
_.filter(collection, predicate)
Syntax of _.filter()
Parameters
This method accepts the following parameters:
collection: This is the collection to be iterated.predicate: This is the function that is checked against the values of the array in every iteration.
Return value
This method returns a new array containing the filtered elements.
Example
Let’s look at an example of finding items in an array based on certain criteria using the _.filter() method in the code snippet below:
Explanation
In the HTML tab:
- Line 5: We import the
lodashscript.
In the JavaScript tab:
- Line 2–7: We create an array of objects.
- Line 10: We use the
_.filter()method to find all the people whose designation isSoftware Engineer. - Line 13: We print the output to the console.