Search code examples
iosobjective-cnsmutablearraynsset

removing duplicates from NSMutableArray with NSSet


I am trying to set up a NSSet to remove all duplicates from a NSMutableArray of NSDictionary Objects, However I am not sure on how to set one of the values needed for creating the NSSet to an element in the NSDictionary Objects of the NSMutableArray... hopefully that makes sense.

This is what the NSDictionary looks like

ID = 22;
SERIESID = 33;
YEAREND = 2002;
YEARSTART = 1996;

This is my code so far

NSSet *uniqueElements = [NSSet setWithArray:yearArray];

// iterate over the unique items
for(id element in uniqueElements) {
    // create new NSArray of unique entries
}

I would like to know how to create a unique yearArray based off the SERIESID value of each NSDictionary in the yearArray.

any help would be appreciated.


Solution

  • You can try this

    NSMutableArray *resultantArray = [NSMutableArray array];
    
    for(NSDictionary *dict in yearArray)
    {
      NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SERIESID == %@",
                                              [dict valueForKey:@"SERIESID"]];
    
      NSArray filteredArray = [resultantArray filteredArrayUsingPredicate:predicate];
    
      if(![filteredArray count])
      {
        [resultantArray addObject:dict];
      }  
    }