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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With