Rob B
Rob B

Reputation: 1299

Check if an array contains elements of another array in swift

I need to check if an array contains at least one or more elements of another array and print them out in swift. This is my situation:

var array1 = ["user1", "user2", "user3", "user4"]
var array2 = ["user3, "user5", "user7", "user9, "user4"]

//I need to get back an array that says that both the arrays contains ex. "user3" and "user4"

I searched the web but i only found the opposite answer that helps t check if there is a difference between 2 arrays using array.symmetricDifference()

Any helps??? Thanks

Upvotes: 7

Views: 5609

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236360

You can simply create a set from your first collection and get its intersection with the other collection:

let array1 = ["user1", "user2", "user3", "user4"]
let array2 = ["user3", "user5", "user7", "user9", "user4"]
let intersection = Array(Set(array1).intersection(array2)) // ["user4", "user3"] 

Note that the order of the resulting collection is unpredictable. If you would like to preserve the order of the first collection you can create a set of the second collection and filter the elements that cannot be inserted to it:

var set = Set(array2)
let intersection = array1.filter { !set.insert($0).inserted }  // ["user3", "user4"]

You can also create your own intersection method on RangeReplaceableCollection:

extension RangeReplaceableCollection {
    func intersection<S: Sequence>(_ sequence: S) -> Self where S.Element == Element, Element: Hashable {
        var set = Set(sequence)
        return filter { !set.insert($0).inserted }
    }
}

Usage:

let intersection = array1.intersection(array2)  // ["user3", "user4"]

Upvotes: 13

Related Questions