Here is an example of the dataset:
[
{
"crystal_name": "African Tourmaline",
"properties": ["Grounding", "Protection"]
},
{
"crystal_name": "Amazonite",
"properties": ["Calming", "Balance", "Truth"]
},
....
]
I’m trying to figure out how to filter the items when the user selects one or more properties..
For example if the user selects "Grounding".. then all the items with "grounding" should appear and if the user selects "calming" and "balance" then only the items with those properties should appear.
I’m new to React.. So I tried the following code:
const filterItems = () => {
if(selectedFilters.length > 0) {
let tempItems = selectedFilters.map((selectedCategory) => {
let temp = crystals.filter((crystal) => {
let flag = 0;
for(let i=0; i<crystal.properties.length; i++) {
if(crystal.properties[i] === selectedCategory) {
flag = 1;
break;
}
}
if(flag === 1) return crystal;
});
return temp;
})
console.log(crystalsToShow);
console.log(tempItems);
setCrystalsToShow(tempItems.flat());
} else {
setCrystalsToShow([...crystals]);
}
};
But according to this logic it will show the items even if one of them will be present in the set of values in array.
>Solution :
Here’s a revised version of your filterItems
function that filters the crystals based on all selected categories:
const filterItems = () => {
if (selectedFilters.length > 0) {
const filteredCrystals = crystals.filter((crystal) => {
return selectedFilters.every((selectedCategory) => {
return crystal.properties.includes(selectedCategory);
});
});
setCrystalsToShow(filteredCrystals);
} else {
setCrystalsToShow([...crystals]);
}
};