5

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.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 2
    If you can post your partial solution as well, it will be easier for others to help you improve it. – Udith Gunaratna Aug 21 '20 at 10:41
  • 1
    Try looking here: https://stackoverflow.com/questions/31831651/javascript-filter-array-multiple-conditions/44807918 and here: https://gist.github.com/jherax/f11d669ba286f21b7a2dcff69621eb72 – Magiczne Aug 21 '20 at 10:41

1 Answers1

5

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);
trincot
  • 317,000
  • 35
  • 244
  • 286