1

I can filter with:

let users = [{'name': 'john', 'age': '20'},{'name': 'jeff', 'age': '2'}

_.filter(users, { 'name': 'john', 'age': '20');

The above will get the user john, but how can I specify multiple options for each array?

For example, I want to get people called john and jeff who are aged 20, something like:

_.filter(users, { 'name': 'john' | 'jeff', 'age': '20');

How can I do this with lodash?

1

3 Answers 3

4

You can use a function as the second argument:

_.filter(users, obj => (obj.name == 'john' || obj.name == 'jeff') && obj.age == '20'));
Sign up to request clarification or add additional context in comments.

Comments

1
var arr = ['barney','fred']
_.filter(users, (user) => {
  // You can put the required conditions here.
  return arr.indexOf(user.user) >=0 && user.age > '20';

});

This is one way to do it where you can specify any conditions. Since you have array of required names, you can do it for multiple names and you can do the same with age.

Comments

1

another flexible solution, just add conditions:

const res = _.filter(users, ({ name, age }) => _.every([
    _.includes(['john', 'jeff'], name),
    _.includes(['20'], age)
]));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.