How to use _.filter() In Lodash
The _.filter() method extract objects from the “orders” array where the “status” property equals ‘pending’. It returns an array containing the filtered objects, representing pending orders.
Syntax:
_.filter( collection, predicate )
Example: The example below shows how to use Lodash to Find and Return an Object from Array Using _.filter().
const _ = require('lodash');
const orders = [
{ id: 1, status: 'pending' },
{ id: 2, status: 'shipped' },
{ id: 3, status: 'pending' },
];
const pendingOrders = _.filter(orders,
order => order.status === 'pending');
console.log(pendingOrders);
Output:
[{ id: 1, status: 'pending' }, { id: 3, status: 'pending' }]
How to use Lodash to Find & Return an Object from Array ?
JavaScript’s built-in array methods offer basic functionality whereas Lodash, a popular utility library, empowers developers with robust tools for complex array operations.
Below are the methods to find and return an object from array using Lodash:
Table of Content
- Using _.find()
- Using _.findIndex() and _.nth()
- Using _.filter()
Run the command to install Loadsh:
npm i loadash
Contact Us