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

How to filter an array using forEach() inside filter() – Javascript

I have an array of objects and I’d like to filter it based on another array. If filters object value is only one, I can use only filter, but if there are one more values in filters object, nothing show. So use forEach inside the filter and wanted to return fit values. Could you please help me what the issue is? Thanks

Expected result:

[
    {
        "tags": [
            "madewithout__gluten",
            "madewithout__nuts",
        ],
        "metafields": "Side"
    }
]
const data = [
    {
        "tags": [
            "madewithout__gluten",
            "madewithout__nuts",
        ],
        "metafields": "Side"
    },
    {
        "tags": [
            "madewithout__gluten",
        ],
        "metafields": "Side"
    },
    {
        "tags": [
            "madewithout__nuts"
        ],
        "metafields": "Side"
    }
]

const filters = ['gluten', 'nuts'] 

const result = data.filter((v) => {
  filters.forEach((tag) => {
    if(!v.tags.includes(`madewithout__${tag}`))
      return;
  });
});

console.log(result);

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

>Solution :

Based on the semantics of the data you provided, you want to check if all filters are contained in tags:

const result = data.filter((v) => 
    filters.every((tag) => v.tags.includes(`madewithout__${tag}`))
)
const data = [
    {
        "tags": [
            "madewithout__gluten",
            "madewithout__nuts",
        ],
        "metafields": "Side"
    },
    {
        "tags": [
            "madewithout__gluten",
        ],
        "metafields": "Side"
    },
    {
        "tags": [
            "madewithout__nuts"
        ],
        "metafields": "Side"
    }
]

const filters = ['gluten', 'nuts'] 

const result = data.filter((v) => 
    filters.every((tag) => v.tags.includes(`madewithout__${tag}`))
)

console.log(result);
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