Jleibham Jleibham - 1 month ago 8
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.

e.g.

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

filterCategory("Design")


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

Answer

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

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