Skip to content

Instantly share code, notes, and snippets.

@juanlatorre
Forked from diegochavez/multiFilter.js
Created October 14, 2018 21:51
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 juanlatorre/637b55a811b10c411a1ea47a541e5d83 to your computer and use it in GitHub Desktop.
Save juanlatorre/637b55a811b10c411a1ea47a541e5d83 to your computer and use it in GitHub Desktop.
Multi filters an array of objects
/**
* 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)));
}
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