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.
That provides two methods: one called removingDuplicates() that returns an array with duplicates removed, and one called removeDuplicates() that changes the array in place.
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.
Use a dictionary like var unique = [<yourtype>:Bool]() and fill in the values like unique[<array value>] = true in a loop. Now unique.
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 ?? ""}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With