Skip to content

Instantly share code, notes, and snippets.

@silesky
Created January 12, 2018 18:04
Show Gist options
  • Save silesky/787be8424332c142ebdd50637f7c5ade to your computer and use it in GitHub Desktop.
Save silesky/787be8424332c142ebdd50637f7c5ade to your computer and use it in GitHub Desktop.
multipleFilters
/**
* Use multiple filters on an array of object
* @param {Object[]} arr - the array to filter
* example:
* [
* {fruit: 'apple', count: 1, id: 123},
* {fruit: 'pear', count: 4, id: 234},
* {fruit: 'orange', count: 4, id: 456}
* ]
* @param {Object.<Array>} filters - an object with the filter criteria as the property names
* example:
* {
* fruit: ['apple', 'orange'],
* count: [4]
* }
* @returns {Object[]} object array - filtered array of object
*/
export const multipleFilters = (
arr: Object[],
filters: {
[key: string]: any[],
},
): Object[] => {
const filterKeys = Object.keys(filters);
return arr.filter(eachObj => {
return filterKeys.every(eachKey => {
if (!filters[eachKey].length) {
return true; // passing an empty filter means that filter is ignored.
}
return filters[eachKey].includes(eachObj[eachKey]);
});
});
};
@rcdegoma
Copy link

Question: What if the Value are multiple that is delimited by semicolon ";",

Sample Data :
Title multi value = "Station 1;Station 2"
Filter State = Station 1 //This is the user selected in a multi checkbox option

  const filterKeys = Object.keys(filters);
  return arr.filter(eachObj => {
    return filterKeys.every(eachKey => {
      if (!filters[eachKey].length) {
        return true; // passing an empty filter means that filter is ignored.
      }
      **return filters[eachKey].includes(eachObj[eachKey]);** 
      // The current behaviour, it only retrieves the exact data sample is "Station 1"= "Station 1"
    });
  });
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment