So, I have 3 filter boxes. The first is named room, second is named color and the third is named staff.
For every filter box there are multiple values which I can choose, for example for color I can choose the value "blue" or for room "presidential". I pass the name of the filterbox and the chosen value in a function changeBox (for example name: color, value: blue).
With that information I want to filter an array. Of course I want to have multiple filters active, which only show the wanted results which are compatible to my activated filters.
So what I did was using a switch case for every possibility which looked like this:
changeBox(name, value) {
if (name === "color") {
switch (value) {
case "blue":
myArray = myArray.filter(item => item.color === "blue");
break;
}
}
if (name === "room") {
switch (value) {
case "presidential":
myArray = myArray.filter(item => item.room === "presidential");
break;
}
}
}
This works If I have only one filter active. The problem is now, if I activate a second filter it works too. But if I switch the second filter to another value, it doesn’t work. I know it’s because of the myArray.filter. It deletes every value in the array which doesn’t fit to my filter. How can I keep the data without actually overwrite it every time?
4
Answers
You should have all of your filter values at once and filter with them:
To answer your question:
You can copy your data into a new variable:
Now we can always work with filtered. At every start of the filter process we repeat this copy so we always start with the complete dataset.
I would also advise to look into the improvements that the comments and answer have given you.
Here is the complete flow of filtering.
filter
by grabbing the values of the<select>
elementsNote: I added "Green" option to show "No results". You can modify the function to pass this as a custom message.
If you consider to decouple actual filtering logic from UI, you can design some sort of generic multiple filter that can be arbitrarily customized and used on any data.
For example, you can implement it as a function that accepts a collection of filters, and a collection of options with which those filters should be used against the filtered array.