Filtering 2 or more categories in vue.js

Viewed 1035

I have a code where i filtered an array with a specific category.

response.data.items.filter(item => item.category_id === categ_id_1)

Now i want to add more categories in the filter (categ_id_2, categ_id_3). How do i do that?

3 Answers

Assuming the category_id is a primitive (ie string, number, etc), the easiest way I can think of is to maintain a Set of wanted categories and use Set.prototype.has() for filtering.

const categories = new Set(['categ_id_1', 'categ_id_2', ...])

response.data.items.filter(({ category_id }) => categories.has(category_id))

If you're wanting the list to be reactive in Vue, something like this...

data: () => ({
  categoryFilters: ['categ_id_1', 'categ_id_2']
}),
computed: {
  categoryFilterSet () {
    return new Set(this.categoryFilters)
  }
},
methods: {
  async loadAndFilterData () {
    const response = await axios({...}) // just guessing

    const filtered = response.data.items.filter(({ category_id }) =>
      this.categoryFilterSet.has(category_id))
  }
}

The reason for using the computed property is that Vue does not work reactively with Set so you must back it up with an array.

Try it as

response.data.items.filter(item => item.category_id === categ_id_1 ||item.category_id === categ_id_2 ||item.category_id === categ_id_3)

Another way using Array.prototype.includes() which is used to pass/fail the test of filter for each element.

const items = [{
    "a": 1,
    "category_id": "categ_id_1"
}, {
    "a": 2,
    "category_id": "categ_id_2"
}, {
    "a": 3,
    "category_id": "categ_id_3"
}, {
    "a": 4,
    "category_id": "categ_id_4"
}, {
    "a": 5,
    "category_id": "categ_id_5"
}];

const search = ["categ_id_2", "categ_id_3"];

const result = items.filter(e => search.includes(e.category_id));

console.info("result::", result);

Related