PoisonedApps PoisonedApps - 1 year ago 112
Swift Question

Identify Duplicates In Array

I have an array of custom objects and want to know how to identify which objects are duplicates. I know how to remove the duplicates but that is not functionality I'm after. Im using swift 2.


var movies: [Movie] = ["Batman v Superman: Dawn of Justice", "Batman v Superman: Dawn of Justice", "Deadpool"," "Deadpool", "Hardcore Henry", "Jason Bourne", "Jurassic World"]

So i want to show a table view with the list of movies above but with "Batman" and "Deadpool" highlighted.

For more clarity on what I'm trying to achieve look at the screenshot. I have a list of movies that two users select in a previous view controller. I want to display the selected movies in a table view. I want to specifically show if there were movies that both people selected.

enter image description here

Answer Source

Based on your comment I have made a simple example with string arrays, which can easily be converted to your movie type:

let movies = ["Batman","Batman","Flash","Avengers"]
var movieCounts:[String:Int] = [:]    
for movie in movies {
 movieCounts[movie] = (movieCounts[movie] ?? 0) + 1

And you can test it like so:

for (key, value) in movieCounts {
 print("\(key) has been selected \(value) time/s")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download