7

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

6
  • what about basic looping and checking with .contains ? Commented Jul 31, 2020 at 14:21
  • 1
    Don't use arrays. Create two sets and get its intersection. Commented Jul 31, 2020 at 14:25
  • @LeoDabus can you explain more Commented Jul 31, 2020 at 14:26
  • 3
    Set(array1).intersection(Set(array2)) Commented Jul 31, 2020 at 14:27
  • 1
    Array(result) Commented Jul 31, 2020 at 14:30

1 Answer 1

13

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"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.