Is there a way to efficiently filter an array of items based on multiple filter arrays? Each item has various filters, and I want to display only the ones that match all 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"]
}
}
];
I'm attempting to address this issue by iterating through all items and checking if each one satisfies all selected filters.
const filterItems = (items, selectedFilters) => {
const filterKeys = Object.keys(selectedFilters);
return items.filter(item => {
return filterKeys.every(key => {
// Skip empty filters
if (!selectedFilters[key].length) {
return true;
}
return selectedFilters[key].every(filterWord => {
item.filters[key].includes(filterWord);
});
});
});
};
filterItems(items, selectedFilters);
Although the current implementation results in an empty array, the expected output should include the "Item 1" object.