Croftc Croftc - 7 months ago 41
Javascript Question

Underscore where filter

I'm trying to use Underscore's "where" to filter an array of objects, but I can't seem to figure out how to get it to filter multiple values for the same key. For example:

var itemsArr = [{name:"foo", color:"red"}, {name:"bar", color:"blue"}, {name:"bob", color:"yellow"}];

I'm trying to get it to return an array off all items with color "red" AND all items with color "blue"... Is this possible? I've tried

tempArr = _.where(itemsArr, {color:["red", "blue"]});

but that didn't work. If I have to just use _.filter and write out my own predicate I will, but I was just wondering if anyone else had tried to do this and found a solution. Thanks


use filter and contains combination:

_.filter(itemsArr, function(item, index) {
  return _.contains(["red", "blue"], item.color);