[英]How to compare two arrays and remove matching elements from one array in Swift iOS
I have two arrays.我有两个数组。
let array1 = ["Lahari", "Vijayasri"];
let array2 = ["Lahari", "Vijayasri", "Ramya", "Keerthi"];
I want to remove the array1 elements in array2 and print the final array-like我想删除 array2 中的 array1 元素并打印最终的类似数组
result array = ["Ramya", "Keerthi"]
Converting the arrays to Set
s and using subtract
is a simple and efficient method:将数组转换为Set
并使用subtract
是一种简单有效的方法:
let array1 = ["Lahari", "Vijayasri"]
let array2 = ["Lahari", "Vijayasri", "Ramya", "Keerthi"]
let resultArray = Array(Set(array2).subtracting(Set(array1)))
If maintaining the order of array2
is important then you can use filter
with a set -如果保持array2
的顺序很重要,那么您可以使用带有集合的filter
-
let compareSet = Set(array1)
let resultArray = array2.filter { !compareSet.contains($0) }
Paulw11
answer works perfectly. Paulw11
回答完美无缺。 But if ordering in array is important you can do this:但如果按数组排序很重要,您可以这样做:
let reuslt = array2.filter { !array1.contains($0) }
extension Array where Element: Hashable {
func difference(from other: [Element]) -> [Element] {
let thisSet = Set(self)
let otherSet = Set(other)
return Array(thisSet.subtracting(otherSet))
}
}
var array1 = ["Lahari", "Vijayasri"]
let array2 = ["Lahari", "Vijayasri", "Ramya", "Keerthi"]
let a = array2.difference(from: array1) // ["Ramya", "Keerthi"]
只收尾。
array2[array1.count...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.