views:

33

answers:

2

If you have an NSMutableArray with three NSDictionarys like this: { name:steve, age:40; name:steve, age:23; name:paul, age:19 }

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

+1  A: 

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 a NSArray of unique name

Benoît
+2  A: 

Similar to the other answer, you could also do:

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

Or

NSArray * names = [myArray valueForKeyPath:@"@distinctUnionOfObjects.name"];
Dave DeLong
Better solution than mine ! I don't think to use valueForKey for array !
Benoît