Reputation: 338
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
result array = ["Ramya", "Keerthi"]
Upvotes: 2
Views: 6418
Reputation: 1838
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"]
Upvotes: 2
Reputation: 114828
Converting the arrays to Set
s and using subtract
is a simple and efficient method:
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 -
let compareSet = Set(array1)
let resultArray = array2.filter { !compareSet.contains($0) }
Upvotes: 7
Reputation: 4719
Paulw11
answer works perfectly. But if ordering in array is important you can do this:
let reuslt = array2.filter { !array1.contains($0) }
Upvotes: 4