Skip to content

Instantly share code, notes, and snippets.

@dhavalwd
Forked from jherax/filterArray.js
Created August 25, 2017 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhavalwd/eb56b79f4d80fb5393df705889892c6d to your computer and use it in GitHub Desktop.
Save dhavalwd/eb56b79f4d80fb5393df705889892c6d to your computer and use it in GitHub Desktop.
Filters an array of objects with multiple criteria.
/**
* 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]));
});
}
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