Reputation: 113
I have for example two arrays, how do I merge them together, but in the same time get the duplicates. Is there any way to that wihout looping through the whole merged array? My array will have lots of data in it so I don't want to load it slower.
For example:
let arrayone = ["1", "2" ,"3", "4"]
let arraytwo = ["1", "4", "5"]
How do I get in a variable for example: ["1", "4"]?
Upvotes: 1
Views: 93
Reputation: 11242
You are looking for intersection(_:) operation of Set
. You just need to convert the arrays to Set
and convert the result back to String
array.
let duplicates: [String] = Array(Set(arrayone).intersection(Set(arraytwo)))
Upvotes: 3
Reputation: 884
If you want to keep the same order as in original array:
let duplicates = Set(arrayone).intersection(Set(arraytwo))
let orderedDuplicates = arraytwo.filter { duplicates.contains($0)}
Upvotes: 2