sinio
sinio

Reputation: 711

Filter array of objects based on array of strings on object's property

I have an array of objects like:

let food = [apple, orange, peach, pear].

Each object looks something like this:

let apple : Fruit = [
  name: "Apple",
  colors: ["red", "yellow", "green", "orange"]
]

I have another array of strings that the food array should be filtered with:

let avoid = ["red", "yellow"]

I want to create a new array from the food array, with Fruit objects that do not contain any of the colors in the avoid array. So in this case, Apple would not be in the food array because it contains both red and yellow.

Thanks!

Upvotes: 0

Views: 82

Answers (2)

Smbat Poghosyan
Smbat Poghosyan

Reputation: 809

let res= food.filter(function(fruit) {
  return !fruit.colors.some(r=> avoid.indexOf(r) >= 0)
})

Upvotes: 0

PGDev
PGDev

Reputation: 24341

Since you haven't given any definition of Fruit object, I'm considering one for reference.

struct Fruit {
    let name: String
    let colors: [String]
}

Creating the food array,

let apple = Fruit(name: "Apple", colors: ["red", "yellow", "green", "orange"])
let orange = Fruit(name: "Orange", colors: ["red", "green", "orange"])
let peach = Fruit(name: "Peach", colors: ["green", "orange"])
let pear = Fruit(name: "Pear", colors: [ "green"])
let food = [apple, orange, peach, pear]

To filter the food array using avoid array, we can use Set intersection method, i.e.

let avoid = ["red", "yellow"]
let filteredFruits = food.filter { return Set($0.colors).intersection(avoid).isEmpty }
print(filteredFruits.map({ $0.name })) //["Peach", "Pear"]

filteredFruits will contain objects - pear and peach

Upvotes: 4

Related Questions