0

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

1 Answer 1

1

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)
    )
);
Sign up to request clarification or add additional context in comments.

6 Comments

.every works really well, thank you so much. Though I do seem to get a some() is not a function error when I use your first answer
Is result.allergens an array? If so, it should work. Your code has [ 0: "nut-free", 1: "milk-free" ] which is invalid syntax but looks kind of like an array. Array literals don't have key-value pairs, only values, and Array.prototype.some exists.
It is yeah, key value pairs. If I copy your second answer and change every to some it works so not sure if there is a genuine syntax error in the first one?
.every is the answer I needed for sure, but just an FYI on the .some answer
Yes, your code of [ 0: "nut-free", 1: "milk-free" ] is definitely a syntax error, just try it: const someArr = [ 0: "nut-free", 1: "milk-free" ] will throw
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.