mootymoots
mootymoots

Reputation: 4575

Count values in NSDictionarys within an NSArray

I have an NSArray full of NSDictionary objects. Each dictionary object has a key:value:

color: red

Amongst other keys... color could be one of many colors that are user generated.

I would like to be able to extract each color and count how many I have of each, so:

red: 3 dictionaries yellow: 4 dictionaries

etc... How exactly would this be possible? Just iterate through the dictionaries until you find a unique color, then search the array using NSPredicate again for that color, rinse, repeat?

Upvotes: 0

Views: 295

Answers (1)

jtbandes
jtbandes

Reputation: 118731

You could just maintain a dictionary mapping color to the number of dictionaries with that color. For example:

NSMutableDictionary *counts = [NSMutableDictionary dictionary];
for (NSDictionary *dict in myArray) {
    NSString *color = [dict objectForKey:@"color"];
    NSNumber *val = [counts objectForKey:color];
    val = [NSNumber numberWithUnsignedInteger:1+[val unsignedIntegerValue]];
    [counts setObject:val forKey:color];
}

Upvotes: 2

Related Questions