-
-
Save vpotap/16a14735694f275241614804f747325f to your computer and use it in GitHub Desktop.
Filters an array of objects with multiple criteria.
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
/** | |
* Filters an array of objects with multiple criteria. | |
* | |
* @param {Array} array: the array to filter | |
* @param {Object} filters: an object with the filter criteria as the property names | |
* @return {Array} | |
*/ | |
function multiFilter(array, filters) { | |
const filterKeys = Object.keys(filters); | |
// filters all elements passing the criteria | |
return array.filter((item) => { | |
// dynamically validate all filter criteria | |
return filterKeys.every(key => !!~filters[key].indexOf(item[key])); | |
}); | |
} |
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 }, | |
{ name: "D", color: "Green", size: 50 }, | |
]; | |
// the value of each key is an array with the values to filter | |
let filters = { | |
color: ["Blue", "Black"], | |
size: [70, 50] | |
}; | |
// filter the products array by color: blue and black | |
// and also by size: 70 and 50 | |
var filtered = multiFilter(products, filters); | |
console.info('Filtered:'); | |
console.log(filtered); | |
/* expected | |
[ | |
{ name: "A", color: "Blue", "size": 50 }, | |
{ name: "C", color: "Black", "size": 70 } | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment