Intersection of two arrays in Swift

This tutorial is about finding the common elements in given two arrays in Swift. This can also be called an intersection of two arrays in Swift. For example, our task is to find the common elements in two arrays, also it can be used to find the common elements in more than two arrays.

Demonstration- The given arrays are-

[1,2,3]

[2,3,4]

So the intersection of these two arrays would be- [2,3]

For this, we need to create arrays-

let arrays = [[1,2,3], [2, 3, 4]]

We have created two arrays named consisting of integers. Now we need to find out the intersection or we can say that we now need to find out the common elements in the two arrays.

Now we will take the first array elements in firstarray as

let firstarray = arrays.first ?? []

?? operator in Swift is nil coalescing operator which returns the first non-null value. If you try to print firstarray, the output will be [1,2,3]

Now we need to find common elements in these arrays. The syntax would be-

let commonElements = arrays.dropFirst().reduce(Set(firstarray)) { (result, list)  in
    result.intersection(list)
    
}

So we have the common elements stored in the commonElements.

Last but not least we need to print the commonElements using-

print(commonElements)
Output:-
[2, 3]

We have accomplished the task to print the intersection of two arrays.

Leave a Reply

Your email address will not be published. Required fields are marked *