Marcus Christiansen
Marcus Christiansen

Reputation: 3197

Lodash _.filter function must only meet ONE condition

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.

Upvotes: 23

Views: 64981

Answers (2)

Ivan Pirus
Ivan Pirus

Reputation: 1076

Also works second solution in Vue.js

users.filter(user => {
                return user.age == 36 || user.active;
            });

Upvotes: 1

npe
npe

Reputation: 15699

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');

Upvotes: 59

Related Questions