I have an array of objects to be filtered:
[
{
"name": "Apple",
"age": 24,
"model": "Android",
"status": "Under development",
},
{
"name": "Roboto",
"age": 24,
"model": "Apple",
"status": "Running",
},
.
.
.
.
]
I need to filter the array using multiple parameters using JavaScript's filter
method.
I have got a partial solution but could not get the expected output.
The filter should also work with multiple values for a single attribute.
E.g., age=54,23
or model="Android","Apple"
etc.
I'm trying to mimic the working of filters just like that of an e-commerce site, where we can compare all of a product’s attributes and customer’s chosen tags to output a filtered list of products.
To apply multiple filters:Click the drop-down arrow for the column you want to filter. In this example, we will add a filter to column D to view information by date. The Filter menu will appear. Check or uncheck the boxes depending on the data you want to filter, then click OK.
If you format your filter conditions just like an object in your data array, but with values being arrays of possible values, then you can use the filter
method as follows:
let data = [
{
"name": "Apple",
"age": 24,
"model": "Android",
"status": "Under development",
}, {
"name": "Roboto",
"age": 24,
"model": "Apple",
"status": "Running",
}, {
"name": "Samsung",
"age": 26,
"model": "Blueberry",
"status": "Running",
},
];
let filter = {
"name": ["Roboto", "Ericsson"],
"age": [22, 24, 26],
};
let res = data.filter(obj =>
Object.entries(filter).every(([prop, find]) => find.includes(obj[prop])));
console.log(res);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With