Ok, this is my solution to solve this problem:
-(NSMutableArray *)sortByFreq : (NSArray *)inArray { //first calculate counts NSMutableDictionary *d = [NSMutableDictionary new]; for (NSString *s in inArray) { if (![d objectForKey:s]) { [d setValue:[NSNumber numberWithInt:1] forKey:s]; }else{ [d setValue:[NSNumber numberWithInt:[[d objectForKey:s] intValue]+1] forKey:s]; } } //create help array with keys to sort NSMutableDictionary *d2 = [NSMutableDictionary new]; for (NSString *key in d) { [d2 setValue:key forKey:[NSString stringWithFormat:@"%@_%@", [d objectForKey:key], key]]; } //sort keys NSArray *sortedArray = [[d2 allKeys] sortedArrayUsingComparator: ^NSComparisonResult(id obj1, id obj2){ NSArray *a1 = [obj1 componentsSeparatedByString:@"_"]; NSArray *a2 = [obj2 componentsSeparatedByString:@"_"]; //compare if ([[a1 objectAtIndex:0] isEqualToString:[a2 objectAtIndex:0]]) { return [[a1 objectAtIndex:1] compare:[a2 objectAtIndex:1]]; } return [obj2 compare:obj1]; }]; //create array to output NSMutableArray *outputArray = [NSMutableArray new]; for (NSString *key in sortedArray) { [outputArray addObject:[d2 objectForKey:key]]; } return outputArray; }
i hope this help.
You can call it like this:
NSLog(@"%@", [self sortByFreq:[[NSArray alloc] initWithObjects:@"c", @"a", @"b", @"c", @"b", nil]]); NSLog(@"%@", [self sortByFreq:[[NSArray alloc] initWithObjects:@"c", @"c", @"c", @"a", @"b", nil]]); NSLog(@"%@", [self sortByFreq:[[NSArray alloc] initWithObjects:@"b", @"a", @"a", @"a", @"c", nil]]); NSLog(@"%@", [self sortByFreq:[[NSArray alloc] initWithObjects:@"c", @"c", @"b", @"b", @"a", nil]]);
output will be:
(b,c,a) (c,a,b) (a,b,c) (b,c,a)