Unique elements from NSMutableArray with NSDictionary elements?

If you have an NSMutableArray with three NSDictionary, for example:

{ 
  name:steve, age:40;
  name:steve, age:23;
  name:paul, age:19
}

How to turn this into an array with only two lines {steve, paul}. In other words, the unique names from the original NSMutableArray? Is there a way to do this using blocks?

+3
source share
2 answers

something like that:

NSMutableSet* names = [[NSMutableSet alloc] init];

[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)) {
  [names addObject:[obj valueForKey:@"name"]];
}];

[names allObjects] will return an NSArray unique name

+4
source

As with the other answer, you can also:

NSSet * names = [NSSet setWithArray:[myArray valueForKey:@"name"]];

or

NSArray * names = [myArray valueForKeyPath:@"@distinctUnionOfObjects.name"];
+15
source

Source: https://habr.com/ru/post/1770539/


All Articles