Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.
The _.filter() method iterates over elements of collection, returning an array of all elements predicate returns true.
Note: This method is not similar to the _.remove() method as this method returns a new array.
Syntax:
_.filter( collection, predicate )
Parameters: This method accepts two parameters as mentioned above and described below:
- collection: This parameter holds the collection to iterate over.
- predicate: This parameter holds the function invoked per iteration.
Return Value: This method returns the new filtered array.
Example 1:
const _ = require( "lodash" );
var users = [
{ 'user' : 'luv' ,
'salary' : 36000,
'active' : true },
{ 'user' : 'kush' ,
'salary' : 40000,
'active' : false }
];
let filtered_array = _.filter(
users, function (o) {
return !o.active;
}
);
console.log(filtered_array);
|
Output:
[ { user: 'kush', salary: 40000, active: false } ]
Example 2:
const _ = require( "lodash" );
var users = [
{ 'user' : 'luv' ,
'salary' : 36000,
'active' : true },
{ 'user' : 'kush' ,
'salary' : 40000,
'active' : false }
];
let filtered_array = _.filter(users,
{ 'salary' : 36000, 'active' : true }
);
console.log(filtered_array);
|
Output:
[ { user: 'luv', salary: 36000, active: true } ]
Example 3:
const _ = require( "lodash" );
var users = [
{ 'user' : 'luv' ,
'salary' : 36000,
'active' : true },
{ 'user' : 'kush' ,
'salary' : 40000,
'active' : false }
];
let filtered_array =
_.filter(users, [ 'active' , false ]);
console.log(filtered_array);
|
Output:
[ { user: 'kush', salary: 40000, active: false } ]
Example 4:
const _ = require( "lodash" );
var users = [
{ 'user' : 'luv' ,
'salary' : 36000,
'active' : true },
{ 'user' : 'kush' ,
'salary' : 40000,
'active' : false }
];
let filtered_array =
_.filter(users, 'active' );
console.log(filtered_array);
|
Output:
[ { user: 'luv', salary: 36000, active: true } ]