如何比较两个数组?并获得不在另一个元素中的元素?

时间:2015-07-25 23:00:35

标签: ios swift

假设我们有两个数组:

var a = ["Tom", "Harry", "jim", "Allen"]
var b = ["Tom", "Harry", "jim", "Allen", "Chloe", "Jasmine"]

现在我想要一个包含以下元素的数组:

var requiredArray = ["Chloe","Jasmine"]

2 个答案:

答案 0 :(得分:7)

您的规范不够具体,但这是一种简单的方法:

var a = ["Tom", "Harry", "jim", "Allen"]
var b = ["Tom", "Harry", "jim", "Allen", "Chloe", "Jasmine"]
let c = Array(Set(b).subtract(a))

答案 1 :(得分:6)

另一种方法是使用filter(请参阅here):

  let result = b.filter { !a.contains($0) }