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

Viewed 52

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);

2 Answers

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);

Instead of .forEach, use .some

const result = data.filter((v) => {
  return !filters.some((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) => {
  return !filters.some((tag) => !v.tags.includes(`madewithout__${tag}`))
});
console.log(result);


Issues with your code

  1. Array.forEach does not return anything. So your return does not break loop or return value.
  2. Your Array.filter does not have return statement. Due to this, by default everything is falsy (return undefined) and hence empty array
Related