Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to filter array values by multiple values by using underscore?

I have the following array of values:

[
   {
     id: 1,
     field: 'map'
   },
   {
     id: 2,
     field: 'dog'
   },
   {
     id: 3,
     field: 'map'
   }
]

I need to find out elements with field equals dog and map. I know I could use the _.filter method and pass an iterator function, but what I want to know is whether or not there's a better solution to this issue where I could pass search field and possible values. Could someone provide a better way of doing so?

EDIT::

I could use the following approach:

_.where(array, {field: 'dog'})

But here I may check only one clause

like image 544
Erik Avatar asked Oct 20 '13 09:10

Erik


2 Answers

_.filter(data, function(item){ return item.field === 'map' || item.field === 'dog'; })

If you want to create a function which accepts field and values it can look like this:

function filter(data, field, values) {
    _.filter(data, function(item){ return _.contains(values, item[field]); })
}
like image 84
vkurchatkin Avatar answered Sep 19 '22 20:09

vkurchatkin


Just pass your filter criteria as the third parameter of _.filter(list, predicate, [context]) which is then set as the context (this) of the iterator:

var data = [
  { id: 1, field: 'map'   },
  { id: 2, field: 'dog'   },
  { id: 3, field: 'blubb' }
];

var filtered = _.filter(
  data,
  function(i) { return this.values.indexOf(i.field) > -1; },
  { "values": ["map", "dog"] } /* "context" with values to look for */
);

console.log(filtered);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
like image 38
Andreas Avatar answered Sep 19 '22 20:09

Andreas