Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a multi-filter function to filter out multiple attributes?

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.

like image 536
Anandhan Sreekumar Avatar asked Aug 21 '20 10:08

Anandhan Sreekumar


People also ask

How do you use multiple filters in Excel?

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.


1 Answers

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);
like image 119
trincot Avatar answered Oct 01 '22 16:10

trincot