Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
84
rated 0 times [  89] [ 5]  / answers: 1 / hits: 63399  / 9 Years ago, thu, july 23, 2015, 12:00:00

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.


More From » arrays

 Answers
28

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

[#65707] Tuesday, July 21, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlynd

Total Points: 470
Total Questions: 108
Total Answers: 120

Location: Faroe Islands
Member since Thu, Apr 8, 2021
3 Years ago
;