Filter array of objects by multiple properties and values

Is it possible to filter an array of objects by multiple values?

E.g in the sample below can I filter it by the term_ids 5 and 6 and type car at the same time?

[  
   {  
      "id":1,
      "term_id":5,
      "type":"car"
   },
   {  
      "id":2,
      "term_id":3,
      "type":"bike"
   },
   {  
      "id":3,
      "term_id":6,
      "type":"car"
   }
]

Definitely up for using a library if it makes it easier.


Solution 1:

You can do it with Array.filter

var data = [{
    "id": 1,
    "term_id": 5,
    "type": "car"
  },
  {
    "id": 2,
    "term_id": 3,
    "type": "bike"
  },
  {
    "id": 3,
    "term_id": 6,
    "type": "car"
  }
];

var result = data.filter(function(v, i) {
  return ((v["term_id"] == 5 || v["term_id"] == 6) && v.type == "car");
})

console.log(result)

Solution 2:

You can do this with plain js filter() method and use && to test for both conditions.

var data = [{"id":1,"term_id":5,"type":"car"},{"id":2,"term_id":3,"type":"bike"},{"id":3,"term_id":6,"type":"car"}];

var result = data.filter(function(e) {
  return [5, 6].includes(e.term_id) && e.type == 'car'
});

console.log(result);

Solution 3:

The following function will help you out.

    nestedFilter = (targetArray, filters) => {
          var filterKeys = Object.keys(filters);
          return targetArray.filter(function (eachObj) {
            return filterKeys.every(function (eachKey) {
              if (!filters[eachKey].length) {
                return true; 
              }
              return filters[eachKey].includes(eachObj[eachKey]);
           });
       });
    };

Use this function with filters described as below:

var filters = {
    "id": ["3"],
    "term_id": ["6"],
    "type": ["car","bike"]
}

Dont pass empty array. If there are no values in the array, skip that property in the filters.

The result will be filtered array.