I know this question has been asked before, but existing solutions do not seem to work for my case. I am trying to filter out data on the basis of multiple properties/values in a varied array of objects.
My sample data looks like this:
const products = [
{ name: 'A', color: 'Blue', size: 50, locations: 'USA' },
{ name: 'B', color: 'Blue', size: 60, locations: 'Europe' },
{ name: 'C', color: 'Blue', size: 30, locations: 'Europe' },
{ name: 'D', color: 'Black', size: 70, locations: 'Japan' },
{ name: 'E', color: 'Green', size: 50, locations: 'Europe' },
{ name: 'F', color: 'Blue', size: 50, locations: 'Brazil' },
{ name: 'G', color: 'Black', size: 40, locations: 'Australia' },
];
This is what I require the filters result to be:
const filters_one = ['Blue'];
const requiredResult_One = [
{ name: 'A', color: 'Blue', size: 50, locations: 'USA' },
{ name: 'B', color: 'Blue', size: 60, locations: 'Europe' },
{ name: 'C', color: 'Blue', size: 30, locations: 'Europe' },
{ name: 'E', color: 'Blue', size: 50, locations: 'Brazil' },
]
const filters_two = ['Blue', 'Europe'];
const requiredResult_Two = [
{ name: 'B', color: 'Blue', size: 60, locations: 'Europe' },
{ name: 'C', color: 'Blue', size: 30, locations: 'Europe' },
]
----------OR-------------------------
const filters_three = ['Black'];
const requiredResult_three = [
{ name: 'D', color: 'Black', size: 70, locations: 'Japan' },
{ name: 'G', color: 'Black', size: 40, locations: 'Australia' },
]
const filters_four = ['Black', 'Japan'];
const requiredResult_Four = [
{ name: 'D', color: 'Black', size: 70, locations: 'Japan' },
]
this is what I have achieved so far:
const filterdata = (products, filter) => {
// where, filter can be equal to *filters_one*, *filters_two*, *filters_three*,
or *filters_four* anyone of it. //
const keysExact = ['color', 'locations'];
const valuesExact = filter.map(col => col.toLowerCase());
const resultExact = products.filter((prod) =>
keysExact.every((key) => valuesExact.includes(prod[key].toLowerCase()))
);
console.log(resultExact);
};
This seems to work partially or not looks like a good approach to me. If anyone can help me with a way better solution on this, will be really helpful.
Thanks in advance!