Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping duplicates in NSArray

I have an NSArray containing custom objects, for example:

[A, A, B, C, A, D, E, B, D]

What is the best way to group these items so the end result resembles this?

A: 3
B: 2
C: 1
D: 2
E: 1

Please note that the duplicates are all different instances that have the same properties, but I have overridden isEqual: for this.

like image 733
pixelfreak Avatar asked Dec 05 '11 20:12

pixelfreak


1 Answers

The simplest way is probably to use an NSCountedSet. You can use [NSCountedSet setWithArray:myArray] to produce a counted set of your array, and then you can iterate over the set's contents to find out the count of each object in the set. Note that it won't be sorted.

Also note that you'll need to provide a sensible implementation of -hash for this to work, since you only said you overrode -isEqual:. You also need to override -compare: if you need a sorted list of results.

Here's a quick method that takes your array and prints the count of each element, sorted:

void printCountOfElementsInArray(NSArray *ary) {
    NSCountedSet *set = [NSCountedSet setWithArray:ary];
    NSArray *objs = [[set allObjects] sortedArrayUsingSelector:@selector(compare:)];
    for (id obj in objs) {
        NSLog(@"%@: %d", obj, [set countForObject:obj]);
    }
}
like image 121
Lily Ballard Avatar answered Sep 28 '22 15:09

Lily Ballard