根据对象属性上的字符串数组过滤对象数组

时间:2019-05-22 07:42:36

标签: arrays swift

我有一个对象数组,例如:

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不会出现在食物数组中,因为它同时包含Applered

谢谢!

2 个答案:

答案 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数组foodavoid数组,我们可以使用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将包含对象-pearpeach

答案 1 :(得分:0)

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