A
A
antpv2018-08-20 17:11:38
JavaScript
antpv, 2018-08-20 17:11:38

What's the best practice to filter data by multiple values?

Let's say we have an object that simply stores the values ​​of checkboxes and is updated accordingly every time any checkbox changes:

let state = {
  's': false,
  'm': false,
  'l': false
} //для абстракции, s / m / l - размеры одежды

We also have an array of objects with clothes, the size is specified in the size property
[...{
value: ...,

<b>size: 's'</b>

value: ...
}...]

Every time we change the checkbox, we get inside the filterItems function.
Finished with the input data, now the questions. What is the best practice/algorithm/pattern for sorting items by checkbox values ​​(in this case)?
Here's how I described the function (if I'm too lazy to delve into it, I described the code in a nutshell below):
function filterItems() {
  let filtered = [];

  filtered = filtered.concat(items.filter((item) => {
    if (state['s'] && item.size === 's') {
        return item;
    }
  }))
  
  filtered = filtered.concat(items.filter((item) => {
    if (state['m'] && item.size === 'm') {
        return item;
    }
  }))
  
  filtered = filtered.concat(items.filter((item) => {
    if (state['l'] && item.size === 'l') {
        return item;
    }
  }))

  return filtered;
}

An empty array has been created to contain the filtered objects.
I use a conditional for each checkbox, if the checkbox is enabled (for example by size s) - we filter the array, and all things with size s get into the new array.
And so for each size, after which I return this new array.
How to do it right? does my approach have the right to life?
I just couldn't think of anything better.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-08-20
@antpv

Как-то уж очень громоздко выглядит. Если я правильно понял, то то, что вам нужно, делается куда проще:

const filterItems = () => items.filter(n => state[n.size]);

S
Stalker_RED, 2018-08-20
@Stalker_RED

Это называется фасетный поиск. Есть готовые библиотеки и фреймворки.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question