10

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

2 Answers 2

21
_.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]); })
}
Sign up to request clarification or add additional context in comments.

1 Comment

The question wasn't exactly clear but the question he's actually asking is how to make it more customizable/generic: "I know I may to use _.filter method and pass iterator function but is there better solution where I could pass search field and possible values?"
8

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>

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.