Merge two arrays with unique values in Swift
We know that there are specific tasks in Swift that require merging two arrays, with unique values, if any element is present more than once.
This blog is related to a similar task where we will try several methods to merge two arrays with no duplicate elements.
You can refer to how to merge two arrays in Swift? for a better understanding of merging two arrays.
We will discuss a few methods of merging two arrays with no duplicates-
Using append
We can use the append
method to concatenate or join two arrays and then use the Set
to remove duplicates as it doesn’t allow duplicates. This is how the flow of the program will go on-
var arr1=[1,2,3] var arr2=[2,4,5] arr1.append(contentsOf: arr2) print(Set(arr1).sorted())
Output-[1, 2, 3, 4, 5]
As we can see our output consists of merged arrays with no duplicate elements present.
Using ‘+’ operator to merge two arrays without duplicates in Swift
The above method can be modified with the ‘+’ operator and then again convert the result into a set to remove the duplicate elements. The snippet part would be-
var arr1=[1,2,3] var arr2=[2,4,5] var merged=arr1+arr2 print(Set(merged).sorted())
Output-[1,2,3,4,5]
Using joined() method to merge two arrays with unique values
As we know joined()
method is used to concatenate all the elements present in an array. We will use this to accomplish our task as-
var arr1=[1,2,3] var arr2=[2,4,5] var merged=[arr1,arr2].joined() print(Set(merged).sorted())
Output-[1,2,3,4,5]
We have discussed three methods to merge two arrays in Swift and also not allow duplicates to be present simultaneously in the result array.
Leave a Reply