Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash _.filter function must only meet ONE condition

Tags:

I am currently using the Lodash _.filter() function to filter objects which meet a specific condition based on the user search, which could either be a street address, town or country.

I have extracted the search string and want to filter this against several values within each object and must return the object if the string is found in any of those keys.

To explain I want to use the example from the website.

var users = [   { 'user': 'barney',  'age': 36, 'active': true },   { 'user': 'fred',    'age': 40, 'active': false },   { 'user': 'pebbles', 'age': 1,  'active': true } ];  // using the `_.matches` callback shorthand _.result(_.find(users, { 'age': 1, 'active': true }), 'user'); 

In this example, how would I filter for users who either are 36 years of age OR are active?

According to the documentation it seems that both conditions needs to be met, as per the above example for the object to be returned.

like image 202
Marcus Christiansen Avatar asked Jul 23 '15 12:07

Marcus Christiansen


1 Answers

You can pass a function to _.filter:

_.filter(users, function(user) {     return user.age === 36 || user.active; }); 

and you can use the same technique with _.find:

_.result(_.find(users, function(user) {     return user.age === 36 || user.active; }), 'user'); 
like image 63
npe Avatar answered Sep 27 '22 20:09

npe