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.

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

Also works second solution in Vue.js

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

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Javascript Append Child AFTER Element

Similar Posts