-
-
Save SRatna/71169377ce29144d59b766a5a3f711ea 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] === 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: "Green", size: 60 }, | |
{ name: "C", color: "Black", size: 70 }, | |
{ name: "D", color: "Blue", size: 50 }, | |
]; | |
// the value of each key is an array with the values to filter | |
let filters = { | |
color: "Blue", | |
size: 50 | |
}; | |
// filter the products array by color: blue | |
// and also by size: 50 | |
var filtered = multiFilter(products, filters); | |
console.info('Filtered:'); | |
console.log(filtered); | |
/* expected | |
[ | |
{ name: "A", color: "Blue", "size": 50 }, | |
{ name: "C", color: "Blue", "size": 50 } | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment