panthro
panthro

Reputation: 24059

Filter with multiple values with lodash?

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?

Upvotes: 1

Views: 6184

Answers (3)

stasovlas
stasovlas

Reputation: 7416

another flexible solution, just add conditions:

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

Upvotes: 1

Sujil Maharjan
Sujil Maharjan

Reputation: 1377

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.

Upvotes: 1

mehulmpt
mehulmpt

Reputation: 16587

You can use a function as the second argument:

_.filter(users, obj => (obj.name == 'john' || obj.name == 'jeff') && obj.age == '20'));

Upvotes: 4

Related Questions