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.

Jeevan
  • 756
  • 13
  • 39
  • Possible duplicate of [lodash Filter collection using array of values](http://stackoverflow.com/questions/17251764/lodash-filter-collection-using-array-of-values) – Andreas Jun 15 '16 at 10:43
  • hi, did my answer address your question? – Quannt Jun 17 '16 at 10:18

1 Answers1

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.

Quannt
  • 2,035
  • 2
  • 21
  • 29