-
-
Save sumitk/f15d0d39e77f6f6addc6252bdbebaa7e to your computer and use it in GitHub Desktop.
FILTER BLOG - multi filter
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
| https://medium.com/better-programming/creating-a-multi-filter-function-to-filter-out-multiple-attributes-javascript-react-rails-5aad8e272142 | |
| const category = ['innerwear', 'dress', 'robe', 'pajamas', 'sweater', 'pants']; | |
| const color = ['white', 'black', 'brown', 'navy', 'blue', 'yellow', 'pink', 'purple', 'beige', 'red', 'green']; | |
| const gender = ['unisex', 'girl', 'boy']; | |
| const material = ['modal', 'cotton', 'spandex', 'tencel', 'rayon']; | |
| const collectedTrueKeys = { | |
| color: ['white', 'pink'], | |
| gender: ['girl'], | |
| material: ['cotton'], | |
| cateogry: [] | |
| } | |
| multiPropsFilter = (products, filters) => { | |
| const filterKeys = Object.keys(filters); | |
| return products.filter(product => { | |
| return filterKeys.every(key => { | |
| if (!filters[key].length) return true; | |
| // Loops again if product[key] is an array (for material attribute). | |
| if (Array.isArray(product[key])) { | |
| return product[key].some(keyEle => filters[key].includes(keyEle)); | |
| } | |
| return filters[key].includes(product[key]); | |
| }); | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment