Filter array of objects by multiple properties and values

Viewed 54123

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.

4 Answers

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.

Another way to do it is to use lodash filter + reduce.

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

const result = [
  {term_id: 5, type: 'car'},
  {term_id: 6, type: 'car'},
].reduce((prev, orCondition) => prev.concat(_.filter(arr, orCondition)), []);

console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

Related