Lakshmi
Lakshmi

Reputation: 338

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

result array = ["Ramya", "Keerthi"]

Upvotes: 2

Views: 6418

Answers (3)

Hamed
Hamed

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

Paulw11
Paulw11

Reputation: 114828

Converting the arrays to Sets 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

Mac3n
Mac3n

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

Related Questions