I have two arrays:
我有两个数组:
let arr1 = ["one.json", "two.json", "three.json"]
let arr2 = ["one.json", "three.json"]
Now I want to remove all values of arr2
in arr1
, so my expected result in the example above would be let arrFiltered = ["two.json"]
. I know how to handle this using a for-loop, however, I thought there may is an easier and more performance-oriented solution?
现在我想删除arr1中arr2的所有值,所以我在上面的例子中的预期结果将是arrFiltered = [“two.json”]。我知道如何使用for循环来处理这个问题,但是,我认为可能有一个更简单,更面向性能的解决方案?
2 个解决方案
#1
5
You have to use Set
instead of Array
in this case.
在这种情况下,您必须使用Set而不是Array。
let arr1 = Set(["one.json", "two.json", "three.json"])
let arr2 = Set(["one.json", "three.json"])
arr1.subtract(arr2)
Fundamental Set Operations
基本集合运算
The illustration below depicts two sets–a and b– with the results of various set operations represented by the shaded regions.
下图描绘了两组-a和b-,其中各种设定操作的结果由阴影区域表示。
- Use the intersect(_:) method to create a new set with only the values common to both sets.
- 使用intersect(_ :)方法创建一个新集合,其中只包含两个集合共有的值。
- Use the exclusiveOr(_:) method to create a new set with values in either set, but not both.
- 使用exclusiveOr(_ :)方法创建一个新集合,其中包含任一集合中的值,但不能同时创建两者。
- Use the union(_:) method to create a new set with all of the values in both sets.
- 使用union(_ :)方法创建一个包含两个集合中所有值的新集合。
- Use the subtract(_:) method to create a new set with values not in the specified set.
- 使用subtract(_ :)方法创建一个值不在指定集中的新集。
阅读更多
#2
5
Solution using the filter
function
解决方案使用过滤功能
let arr1 = ["one.json", "two.json", "three.json"]
let arr2 = ["one.json", "three.json"]
let arrFiltered = arr1.filter{ !arr2.contains($0) }
#1
5
You have to use Set
instead of Array
in this case.
在这种情况下,您必须使用Set而不是Array。
let arr1 = Set(["one.json", "two.json", "three.json"])
let arr2 = Set(["one.json", "three.json"])
arr1.subtract(arr2)
Fundamental Set Operations
基本集合运算
The illustration below depicts two sets–a and b– with the results of various set operations represented by the shaded regions.
下图描绘了两组-a和b-,其中各种设定操作的结果由阴影区域表示。
- Use the intersect(_:) method to create a new set with only the values common to both sets.
- 使用intersect(_ :)方法创建一个新集合,其中只包含两个集合共有的值。
- Use the exclusiveOr(_:) method to create a new set with values in either set, but not both.
- 使用exclusiveOr(_ :)方法创建一个新集合,其中包含任一集合中的值,但不能同时创建两者。
- Use the union(_:) method to create a new set with all of the values in both sets.
- 使用union(_ :)方法创建一个包含两个集合中所有值的新集合。
- Use the subtract(_:) method to create a new set with values not in the specified set.
- 使用subtract(_ :)方法创建一个值不在指定集中的新集。
阅读更多
#2
5
Solution using the filter
function
解决方案使用过滤功能
let arr1 = ["one.json", "two.json", "three.json"]
let arr2 = ["one.json", "three.json"]
let arrFiltered = arr1.filter{ !arr2.contains($0) }