-
-
Save diegochavez/e9019fedefa0553ce7efc12857739322 to your computer and use it in GitHub Desktop.
Multi filters an array of objects
This file contains hidden or 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
/** | |
* Multi-filter an array of objects | |
* @param {Array} array : list of elements to apply a multiple criteria filter | |
* @param {Object} filters: Contains multiple criteria filters by the property names of the objects to filter | |
* @return {Array} | |
*/ | |
function multiFilter(array, filters) { | |
let filterKeys = Object.keys(filters); | |
// filters all elements passing the criteria | |
return array.filter((item) => filterKeys.every((key) => (filters[key].indexOf(item[key]) !== -1))); | |
} |
This file contains hidden or 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
let products = [ | |
{ name: "A", color: "Blue", size: 50 }, | |
{ name: "B", color: "Blue", size: 60 }, | |
{ name: "C", color: "Black", size: 70 } | |
]; | |
let filters = { | |
color: ["Blue", "Black"], | |
size: [70, 50] | |
}; | |
// expected | |
let expected = [ | |
{ name: "A", color: "Blue", "size": 50 }, | |
{ name: "C", color: "Black", "size": 70 } | |
]; | |
var filtered = multiFilter(products, filters); | |
console.info('Expected'); | |
console.log(expected); | |
console.info('Filtered'); | |
console.log(filtered); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
π @diegochavez Thanks for the mention.
π Also via Git, you can update your fork with the original, e.g.
git remote add upstream [email protected]:f11d669ba286f21b7a2dcff69621eb72.git
git fetch upstream
git reset --hard upstream/master && git push -f origin master
git rebase upstream/master && git push -f origin master
π§