I have a challenge with filtering a large dataset of products based on user input values. Here is an example of my product dataset:
const products = [
{id: 0, name: "Product1", brand: "Theraflu", itemCode: "THE110", price: 5.45},
{id: 1, name: "Product2", brand: "Benadryl", itemCode: "BEN121", price: 7.05},
{id: 2, name: "Product3", brand: "Listerine", itemCode: "LIS204", price: 4.55},
{id: 3, name: "Product4", brand: "Tylenol", itemCode: "TYL116", price: 6.10},
];
I managed to filter the products using different fields in each product object like this:
const keys = ["name", "brand", "itemCode"];
const getFilteredProducts = (filterText) => {
const newProducts = products.filter(product => keys.some(key => product[key].toLowerCase().includes(filterText.toLowerCase())));
return newProducts;
}
console.log(getFilteredProducts("Tylenol"));
The problem arises when I try to combine different fields for filtering, such as:
console.log(getFilteredProducts("product4 Tylenol"));
Unfortunately, this returns an empty array. Is there a way to address this issue without modifying the current filtering functionality?