Get common elements between two arrays in Swift

Get common elements from two arrays in Swift

After this Swift tutorial, you will be able to learn how to get common elements from two different arrays. Finding common items between two arrays is quite an easy task.

Let’s see the code below:

let homeDevices = ["Macbook", "Doorbell", "Smartphone", "TV", "Refrigerator"]
let officeDevices = ["Air Conditioner", "Macbook", "Mouse", "Refrigerator", "CPU"]

// Create new array with common elements
let commonDevices = homeDevices.filter{ officeDevices.contains($0) }

// or
let commonDevices2 = homeDevices.filter(officeDevices.contains)

In the above code, we have two arrays homeDevices and officeDevices. In our code, we have used the filter() and contains() method to find out the common elements between our two Swift arrays.

You can see that we apply the filter method to the first array. Then we apply the contains method and pass it as the parameter inside the filter method. In the end, it will generate a new Swift array that has the elements common in both these arrays.

To verify if the code is successfully able to perform the task, just print commonDevices or commonDevices2 and see the result. It will show the items common in both arrays.

Alternative way

Now let’s see how we can do the task in a different way. This time we are going to use the Intersection of Two sets. The set intersection() is used to find the elements that are common between two or more sets.

See the code below:

let homeDevices = ["Macbook", "Doorbell", "Smartphone", "TV", "Refrigerator"]
let officeDevices = ["Air Conditioner", "Macbook", "Mouse", "Refrigerator", "CPU"]

let commonDevices = Array(Set(homeDevices).intersection(Set(officeDevices)))

In the above code example, we created the same arrays as we did in the previous example above. After that, we used the Set() method to convert our array into the set. Then we use the Set intersection method to find the common items between our two Swift arrays.

The intersection method, can not be applied to arrays. For this reason, we convert our arrays into sets.

In the end, we are again able to create an array that consists of the common elements of two arrays.

Leave a Reply

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