我有一个对象数组,例如:
let food = [apple, orange, peach, pear]
。
每个对象看起来像这样:
let apple : Fruit = [
name: "Apple",
colors: ["red", "yellow", "green", "orange"]
]
我还有另一个字符串数组,应使用food
数组进行过滤:
let avoid = ["red", "yellow"]
我想从food
数组创建一个新数组,其中包含{em>不包含 {{1}中的任何Fruit
中的colors
个对象}}数组。因此,在这种情况下,avoid
不会出现在食物数组中,因为它同时包含Apple
和red
。
谢谢!
答案 0 :(得分:4)
由于您尚未提供Fruit
对象的任何定义,因此我正在考虑提供一个参考。
struct Fruit {
let name: String
let colors: [String]
}
创建food
数组,
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]
要使用filter
数组food
来avoid
数组,我们可以使用Set
intersection
方法,即
let avoid = ["red", "yellow"]
let filteredFruits = food.filter { return Set($0.colors).intersection(avoid).isEmpty }
print(filteredFruits.map({ $0.name })) //["Peach", "Pear"]
filteredFruits
将包含对象-pear
和peach
答案 1 :(得分:0)
let res= food.filter(function(fruit) {
return !fruit.colors.some(r=> avoid.indexOf(r) >= 0)
})