Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Duplicates From Array of Custom Objects Swift

Tags:

I have a custom class defined as follows :

class DisplayMessage : NSObject { var id : String? var partner_image : UIImage? var partner_name : String? var last_message : String? var date : NSDate? } 

Now I have an array myChats = [DisplayMessage]?. The id field is unique for each DisplayMessage object. I need to check my array and remove all duplicates from it, essentially ensure that all objects in the array have a unique id. I have seen some solutions using NSMutableArray and Equatable however I'm not sure how to adapt them here; I also know of Array(Set(myChats)) however that doesn't seem to work for an array of custom objects.

like image 976
Alk Avatar asked Sep 03 '16 13:09

Alk


People also ask

How do you remove duplicates from an array in place in Swift?

That provides two methods: one called removingDuplicates() that returns an array with duplicates removed, and one called removeDuplicates() that changes the array in place.

How do you remove duplicates from an array of objects?

To remove the duplicates from an array of objects:Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.

How do you make an array unique in Swift?

Use a dictionary like var unique = [<yourtype>:Bool]() and fill in the values like unique[<array value>] = true in a loop. Now unique.


2 Answers

Here is an Array extension to return the unique list of objects based on a given key:

extension Array {     func unique<T:Hashable>(map: ((Element) -> (T)))  -> [Element] {         var set = Set<T>() //the unique list kept in a Set for fast retrieval         var arrayOrdered = [Element]() //keeping the unique list of elements but ordered         for value in self {             if !set.contains(map(value)) {                 set.insert(map(value))                 arrayOrdered.append(value)             }         }          return arrayOrdered     } } 

for your example do:

let uniqueMessages = messages.unique{$0.id ?? ""} 
like image 66
Ciprian Rarau Avatar answered Oct 10 '22 22:10

Ciprian Rarau


You can do it with a set of strings, like this:

var seen = Set<String>() var unique = [DisplayMessage] for message in messagesWithDuplicates {     if !seen.contains(message.id!) {         unique.append(message)         seen.insert(message.id!)     } } 

The idea is to keep a set of all IDs that we've seen so far, go through all items in a loop, and add ones the IDs of which we have not seen.

like image 37
Sergey Kalinichenko Avatar answered Oct 10 '22 21:10

Sergey Kalinichenko