0

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?

2
  • 1
    [{"A"}, {"B"}] is syntactically invalid. How does it really look? Use JSON.stringify() on it if you're not sure. Commented Jun 5, 2014 at 18:20
  • [{"A"}, {"B"}] its invalid. ????? Commented Jun 5, 2014 at 18:21

2 Answers 2

2

Assuming that [0: "A", 1: "B"] is actually ["A", "B"], you can use _.contains:

var categoryNames = ["A", "B"];
_.filter(chartOptions.series, function(series) { 
  return _.contains(categoryNames, series.category) 
});

should do what you want.

Sign up to request clarification or add additional context in comments.

1 Comment

Maybe it is worth to replace contains to categoryNames.indexOf(series.category) >= 0 for simplicity
0

More modern javascript:

chartOptions.series.filter(series => categoryNames.includes(series.category))

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.