0

I have array of objects like this

var users = [
  { 'user': 'barney',  'age': 36, 'active': true , 'company':'abc' },
  { 'user': 'fred',    'age': 40, 'active': false, 'company':'pqr' },
  { 'user': 'pebbles', 'age': 1,  'active': true,  'company':'xyz' }
];

i want filter the array of objects where company is abc or xyz so the result should be like this

[
  { 'user': 'barney',  'age': 36, 'active': true , 'company':'abc' },
  { 'user': 'pebbles', 'age': 1,  'active': true,  'company':'xyz' }
];

i am using the loadash like this

console.log(_.filter(users, {'company': 'xyz','company': 'abc'}))

It is not filtering correctly. can anybody help me on this.

2

1 Answer 1

5

Just use the default syntax, this should work

  _.filter(users, function(user) { return user.company == 'abc' || user.company == 'xyz'; });

The short reason that your code didn't work in the first place

_.filter(users, {'company': 'xyz','company': 'abc'})

is because you were passing a javascript object with duplicated property name company hence the second property with value abc overrides the first property. Which means you were actually doing this

_.filter(users, {'company': 'abc'})

This object {'company': 'abc'} will then be passed to _.matches to produce a function, this function will then validate each element of the array.

  var predicate = _.matches({'company': 'abc'});
  predicate( { 'user': 'barney',  'age': 36, 'active': true , 'company':'abc' }); // true
  predicate(  { 'user': 'fred',    'age': 40, 'active': false, 'company':'pqr' }); // false
  predicate(    { 'user': 'pebbles', 'age': 1,  'active': true,  'company':'xyz' }); // false

which results in only barney is returned.

Sign up to request clarification or add additional context in comments.

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.