I am trying to use Underscore to filter an array based on matches in another array.
I have an array chartOptions.series which looks like this
[{category: "A"}, {category: "B"}, {category: "C"}]
I want to filter this array so that I keep only elements that exist in another array called categoryNames, which looks like this
[0: "A", 1: "B"]
Given this scenario I would expect this result
[{category: "A"}, {category: "B"}]
Here's what I have so far
chartOptions.series = _.filter(chartOptions.series, function(series) {
return _.where(categoryNames, {"": series.category});
});
This doesn't work, it doesn't filter anything. What am I missing?
hjing :
Assuming that [0: \"A\", 1: \"B\"] is actually [\"A\", \"B\"], you can use _.contains:\n\nvar categoryNames = [\"A\", \"B\"];\n_.filter(chartOptions.series, function(series) { \n return _.contains(categoryNames, series.category) \n});\n\n\nshould do what you want.",
2014-06-05T18:25:03