Jleibham Jleibham - 1 year ago 62
Javascript Question

filtering an array of objects by an array of strings

I'm filtering an array of objects with the following code:

filterCategory(category: [string]) {
this.projects = this.projects.filter(project => project.category == category);

It works to a degree but I want to refine it so it will return any object that has the category string within.


project: [{
name: "thing1"
category: ["Design", "Web Design"]
}, {
name: "thing2"
category: ["Web Design"]
}, {
name: "thing3"
category: ["Design"]
}, {
name: "thing4"
category: ["Design", "Web Design"]


filterCategory design currently will only return thing3 but I'd like it to return thing1, thing3, and thing4.

Answer Source

JavaScript's Array.indexOf will look at each array value for a match.

project => project.category.indexOf(category) !== -1

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download