Open In App

How to Filter Array of Objects with Lodash Based on Property Value?

Last Updated : 26 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, We need to filter an array of objects based on specific property values. Lodash, a powerful utility library, provides efficient methods for such operations. we will explore how to use Lodash to filter an array of objects by property value, ensuring that you can easily extract and work with the data that meets your criteria.

There are three approaches to filtering an array of objects with Lodash:

Using _.filter() Method

The _.filter() method is commonly used to filter arrays. It returns a new array containing all elements that pass the test implemented by the provided function.

Syntax:

_.filter(array, [predicate])

Example: In this example, _.filter() is used to create a new array containing users whose age is 25.

JavaScript
// solution.js
const _ = require("lodash");

const users = [
    { id: 1, name: "Ram", age: 25 },
    { id: 2, name: "Pawan", age: 30 },
    { id: 3, name: "Ajay", age: 25 },
];

const filteredUsers = _.filter(users, { age: 25 });
console.log(filteredUsers);

Output:

Capture
Output

Using _.reject() Method

The _.reject() method is similar to _.filter(), but it returns a new array with all elements that do not pass the test implemented by the provided function.

Syntax

_.reject(array, [predicate])

Example: In this example, _.reject() creates a new array excluding users whose age is 25.

JavaScript
// solution.js
const _ = require('lodash');

const users = [
    { id: 1, name: 'Ram', age: 25 },
    { id: 2, name: 'Pawan', age: 30 },
    { id: 3, name: 'Ajay', age: 25 }
];

const rejectedUsers = _.reject(users, { age: 25 });
console.log(rejectedUsers);

Output:

Capture2
Output

Using _.remove() Method

The _.remove() method is similar to _.filter(), but it modifies the original array by removing elements that match the condition.

Syntax

_.remove(array, [predicate])

Example: In this example, _.remove() directly modifies the users array by removing elements where the age is 25.

JavaScript
// solution.js
const _ = require('lodash');

const users = [
    { id: 1, name: 'Ram', age: 25 },
    { id: 2, name: 'Pawan', age: 30 },
    { id: 3, name: 'Ajay', age: 25 }
];

_.remove(users, { age: 25 });
console.log(users);

Output:

Capture3
Output

Next Article

Similar Reads