F. Dolha
F. Dolha

Reputation: 113

Merge two arrays and get the duplicates in a variable

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

Answers (2)

Rakesha Shastri
Rakesha Shastri

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

claude31
claude31

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

Related Questions