Jleibham
Jleibham

Reputation: 530

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.

Upvotes: 0

Views: 76

Answers (3)

Jleibham
Jleibham

Reputation: 530

I found another (less code) way to do this with ES6. Instead of project => project.category.indexOf(category) !== -1 you can use .includes to do the same thing so the final code would look like this:

project => project.category.includes(category)

Worked the same for me just a little cleaner if you're using ES6.

Upvotes: 0

silentsod
silentsod

Reputation: 8335

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

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

Upvotes: 2

Adrian Brand
Adrian Brand

Reputation: 21628

project => {
    for (let i = 0; i < project.category.length; i++) {
        if (project.category[i] === category) {
            return true;
        }
    }
    return false;
}

Upvotes: 1

Related Questions