D
D
danilr2019-06-15 21:15:55
Vue.js
danilr, 2019-06-15 21:15:55

How to write a filter?

Help write a filter that works like this - there is an array with filters that the selected objects must match. The array consists of objects that contain flags by which to filter:activeFilter = ['display', 'water', 'gps']

{
 disColor : true,
  water : false,
 gps : true
}

The filter must be independent, that is, if at least one of the flags is true, then include it in the result.
Please help me write this algorithm.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-06-15
@danilr

Let's add a description of the filters to the component. This will be an array of objects containing two properties: name (matches the property name in the elements of the filtered array) and activity (indicates whether this filter should be applied):

data: () => ({
  filters: [
    { name: 'disColor', active: true },
    { name:    'water', active: true },
    { name:      'gps', active: true },
  ],
  ...

Based on this description, we will create controls so that the user can switch the activity of filters:
<label v-for="f in filters">
  <input type="checkbox" v-model="f.active">
  {{ f.name }}
</label>

Finally, apply the filters - let's make a calculated property that will represent the filtered data:
computed: {
  filteredItems() {
    const filters = this.filters.filter(n => n.active);
    return this.items.filter(n => filters.some(f => n[f.name]));
  },
  ...

https://jsfiddle.net/276xgmho/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question