Vue / Lodash filter Array by another array’s values

I’m continuing my JavaScript learning and I’ve come across something that isn’t clear to me to work around.

In my Vue data object I have:

  data: {
    allergenFilter: [],
    categoryFilter: [],
    results: {},
  },

I have an array of checkboxes which allows me to select allergens for products, it populates my allergenFilter Vue property like this:

[
  0: "nut-free",
  1: "milk-free"
]

But I also have a list of allergens that a product has/doesn’t have that I’d like to match the products that include the choices. This is an example from a product:

[
  0:"vegetarian"
  1:"vegan"
  2:"egg-free"
  3:"nut-free"
]

I’ve tried to filter the results by doing this:

  this.results.filter(result =>
    result.allergens.includes(
      this.allergenFilter
    )
  )

But it doesn’t work because of the key:value pairings, so I know the issue, but I’m not entirely sure of how to see if an arrays values are included in another array’s values

Answer

You need another nested loop – check if .some of the allergens are included in the allergenFilter.

this.results.filter(result =>
    result.allergens.some(
        allergen => this.allergenFilter.includes(allergen)
    )
)

If you need all of the allergenFilter to be included, then use .every.

this.results.filter(result =>
    this.allergenFilter.every(
        allergen => result.allergens.includes(allergen)
    )
);