I'm trying to filter an array of items based on multiple filter arrays. Each of the items has a selection of filters, and I need to show only the ones that match all of the selected filters.
const selectedFilters = {
color: ["Red", "Blue"],
type: ["Shirt"],
size: ["M"]
};
const items = [
{
name: "Item 1",
filters: {
color: ["Red", "Blue", "Black"],
type: ["Shirt"],
size: ["M"]
}
},
{
name: "Item 2",
filters: {
color: ["Red"],
type: ["Pants"],
size: ["M"]
}
}
];
This is how I've been trying to solve it. Filter through all of the items - for each filter category that is not empty, go through all the filter words and check that the item matches all of them.
const filterItems = (items, selectedFilters) => {
const filterKeys = Object.keys(selectedFilters);
return items.filter(item => {
return filterKeys.every(key => {
// Ignore empty filters
if (!selectedFilters[key].length) {
return true;
}
return selectedFilters[key].every(filterWord => {
item.filters[key].includes(filterWord);
});
});
});
};
filterItems(items, selectedFilters);
Returns an empty array, should return an array with the "Item 1" object.
returninside theeverycallback:return item.filters[key].includes(filterWord)