0

I have an array of foods, with various objects representing information about each food

var Food = {
    ["Apple","Green","Fruit"],
    ["Basil","Green","Herb"],
    ["Tomato","Red","Fruit"],
    ["Carrot","Orange","Vegetable"],
    ["Zucchini","Green","Vegetable"]
}

I am able to filter this array into a new array using the filter function.

var newArray = Food.filter(function (el) {
  return el[2] == "Fruit" || 
         el[2] == "Vegetable" ||
});

As expected, this produces a new array with the items which are fruits and vegetables.

I would however like to use a separate array with the or logical operator as the criteria for the filtration.

For example I would have an array like this:

var filters = ["Fruit","Vegetable"]

This would then be referenced in the filter function to produce the same result.

I have tried a few things such as building a string as passing it through the function, but I am having problems with not using the || on the final object of the array.

How may I achieve this sucessfully?

Adam Scot
  • 1,371
  • 4
  • 21
  • 41

1 Answers1

1

Use Array#some() in the filter().

For an AND conditional use every() instead of some()

var Food = [
    ["Apple","Green","Fruit"],
    ["Basil","Green","Herb"],
    ["Tomato","Red","Fruit"],
    ["Carrot","Orange","Vegetable"],
    ["Zucchini","Green","Vegetable"]
]

var filters = ["Fruit","Vegetable"];

var newArray = Food.filter(el => filters.some(f => el.includes(f)));
 
console.log(newArray)
charlietfl
  • 170,828
  • 13
  • 121
  • 150