meez
meez

Reputation: 4769

Combine Search and checkbox filters in Vue js

I have to filter a list using a Search input field and als some Checkboxes (filter on a category).

I have both functionalities working independently.

The Search field

computed: {
    getfilteredData() {
      return this.experiences.filter(experience =>
        experience.name.toLowerCase().includes(this.search.toLowerCase()) ||
          experience.category.toLowerCase().includes(this.search.toLowerCase()
        )
      )
    }
  },

The Checkboxes

computed: {
    getfilteredData() {
      if (!this.checkedCategories.length)
        return this.experiences

        return this.experiences.filter(experience => 
          this.checkedCategories.includes(experience.category))
    }
  },

How do I combine those filters? So they are working simultaneously?

Upvotes: 1

Views: 365

Answers (1)

Shawn Pacarar
Shawn Pacarar

Reputation: 413

combining both filters in succession will filter both as an AND statement

getfilteredData() {
    return this.experiences.filter(experience =>
        experience.name.toLowerCase().includes(this.search.toLowerCase()) ||
            experience.category.toLowerCase().includes(this.search.toLowerCase()
        )
    ).filter(experience => 
        // if there are no checkboxes checked. all values will pass otherwise the category must be included
        !this.checkedCategories.length || this.checkedCategories.includes(experience.category)
    )
}

otherwise, you could combine them in one filter with (firstCondition || secondCondition) with the same logic you use above.

I saw your other question that got closed Write my Javascript more cleaner in my Vue js search functionality where I think you could rewrite your function like this

experience => {
    let reg = new RegExp(this.search, 'gi')
    return reg.test(`${experience.name} ${experience.category}`)
}

using g means that your string can be in any position, but you must reconstruct your regex on each test otherwise you can end up with issues found here

Why am I seeing inconsistent JavaScript logic behavior looping with an alert() vs. without it?

using i means it will ignore casing so you don't need to worry about using toLowerCase()

thus your filter can be written like this in one statement

experience => {
    let reg = new RegExp(this.search, 'gi')

    // search input matches AND the checkbox matches
    return reg.test(`${experience.name} ${experience.category}`) && (!this.checkedCategories.length || this.checkedCategories.includes(experience.category))

    // search input matches OR the checkbox matches
    //return reg.test(`${experience.name} ${experience.category}`) || (!this.checkedCategories.length || this.checkedCategories.includes(experience.category))
}

Upvotes: 1

Related Questions