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:

Console
Find item in Lodash

Explanation

In the HTML tab:

  • Line 5: We import the lodash script.

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 is Software Engineer.
  • Line 13: We print the output to the console.

New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources