Home:ALL Converter>Filter an array based on another array

Filter an array based on another array

Ask Time:2014-06-06T02:13:09         Author:Sachin Kainth

Json Formatter

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?

Author:Sachin Kainth,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/24067259/filter-an-array-based-on-another-array
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
yy