soleil
soleil

Reputation: 13095

Sorting an array by number of times an object appears in that array

I'm lost in a sea of sort descriptors, dictionaries, and counted sets. Hoping someone can help me find an easier way.

Starting with a sorted array like this (of NSNumbers):

['7','7','7','5','5','5','5','5','5','3','2','2','2','2']

I want to end up with a sorted array of dictionaries that looks like this:

{'5','6'} //the number 5 appeared 6 times
{'2','4'} //the number 2 appeared 4 times
{'7','3'} //the number 7 appeared 3 times
{'3','1'} //the number 3 appeared 1 time

Upvotes: 0

Views: 139

Answers (1)

Monolo
Monolo

Reputation: 18253

Here is a snippet that does what you are after, based on NSCountedSet

NSArray *numbers = @[@7,@7,@7,@5,@5,@5,@5,@5,@5,@3,@2,@2,@2,@2];

NSCountedSet *countedSet = [NSCountedSet setWithArray:numbers];

NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (NSNumber *num in countedSet) {
    NSUInteger c = [countedSet countForObject:num];
    [result setObject:@(c) forKey:num];
}

Upvotes: 5

Related Questions