0

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.

3 Answers 3

2

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

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

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

2 Comments

this worked! would you mind explaining what the -1 does at the end of the code?
The indexOf function returns -1 if the value is not found, since you're looking for matches you need to check that the return value is not -1. > -1 would be another equivalent means of performing the check.
1
project => {
    for (let i = 0; i < project.category.length; i++) {
        if (project.category[i] === category) {
            return true;
        }
    }
    return false;
}

Comments

0

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.

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.