Created
January 12, 2018 18:04
-
-
Save silesky/787be8424332c142ebdd50637f7c5ade to your computer and use it in GitHub Desktop.
multipleFilters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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]); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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