Skip to content

Instantly share code, notes, and snippets.

@diegochavez
Forked from jherax/filterArray.js
Last active January 16, 2022 12:38
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save diegochavez/e9019fedefa0553ce7efc12857739322 to your computer and use it in GitHub Desktop.
Save diegochavez/e9019fedefa0553ce7efc12857739322 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);
@papuruth
Copy link

Can u pliz tell how to handle lowercase filter conditions

@diegochavez
Copy link
Author

Guys go to the source fork please, this was a POC there's more solutions on @jherax implementation 👍

@jherax
Copy link

jherax commented Feb 13, 2020

🎉 @diegochavez Thanks for the mention.

🚀 Also via Git, you can update your fork with the original, e.g.

  1. Clone your gist
  2. Go to your forked directory
  3. Add upstream with the original gist:
    git remote add upstream git@gist.github.com:f11d669ba286f21b7a2dcff69621eb72.git
  4. Sync with the upstream:
    git fetch upstream
  5. Reset your master with the upstream and push it to server:
    git reset --hard upstream/master && git push -f origin master
  6. Or, if you have custom changes, you can rebase it and push it to server:
    git rebase upstream/master && git push -f origin master

🐧

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment