简体   繁体   English

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

[英]How to compare two arrays? And get the element which are not in the other one?

Let say we have two arrays: 假设我们有两个数组:

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

now i want an array which will have the following elements in it: 现在我想要一个数组,其中包含以下元素:

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

Your spec is insufficiently specific, but this is one easy way: 您的规范不够具体,但这是一种简单的方法:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM