Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter array object by array of Boolean values dynamically

I have my array object in the following format

menuItem = [{
    "name": "MOZZARELLA DI BUFALA & TOMATOES",
    "gluten": true,
    "eggs": false,
    "dairy": true,
     ...
},...

I want to filter hundreds of menuItems by the allergen values (Boolean).

While the following code does the trick:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

menuItem.filter(el => !el.gluten && !el.fish && !el.soy && !el.dairy)"

The allergens are hardcoded and repetitive. I am struggling to make the code dynamic and elegant.

I tried the following solution

menuItem.filter(el => !el[allergens])"
var allergens = ['gluten', 'fish', 'soy', 'dairy']

However, it only works correctly with one allergen value. Multiple values as in the above example do not filter anything.

>Solution :

You could use .some or .every, whichever match your case

const allergens = ['gluten', 'fish', 'soy', 'dairy']

const res = menuItem.filter(
  (el) => !allergens.every((allergen) => el[allergen])
);
// equivalent to `menuItem.filter(el => !el.gluten && !el.fish && !el.soy && !el.dairy)`
const menuItem = [
  {
    name: 'dish A',
    gluten: true,
    fish: true,
    soy: true,
    dairy: true,
  },
  {
    name: 'dish B',
    gluten: true,
    fish: true,
    soy: false,
    dairy: true,
  },
];

const allergens = ['gluten', 'fish', 'soy', 'dairy'];

const res = menuItem.filter(
  (el) => !allergens.every((allergen) => el[allergen])
);

console.log(res);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading