Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicates from array based on a property in Objective-C

I have an array with custom objects. Each array item has a field named "name". Now I want to remove duplicate entries based on this name value.

How should I go about achieving this?

like image 352
Asad Khan Avatar asked Oct 24 '10 07:10

Asad Khan


1 Answers

I do not know of any standard way to to do this provided by the frameworks. So you will have to do it in code. Something like this should be doable:

NSArray* originalArray = ... // However you fetch it
NSMutableSet* existingNames = [NSMutableSet set];
NSMutableArray* filteredArray = [NSMutableArray array];
for (id object in originalArray) {
   if (![existingNames containsObject:[object name]]) {
      [existingNames addObject:[object name]];
      [filteredArray addObject:object];
   }
}
like image 149
PeyloW Avatar answered Sep 27 '22 17:09

PeyloW