Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count duplicates values in NSArray?

Value of my NSArray includes the duplicates. I find the duplicates but now how can I find the no. they repeat?

like image 382
iDev Avatar asked Jul 27 '11 07:07

iDev


2 Answers

You can use NSCountedSet for this. Add all your objects to a counted set, then use the countForObject: method to find out how often each object appears.

like image 147
omz Avatar answered Oct 12 '22 17:10

omz


Example:

NSArray *names = [NSArray arrayWithObjects:@"John", @"Jane", @"John", nil];
NSCountedSet *set = [[NSCountedSet alloc] initWithArray:names];

for (id item in set) {

    NSLog(@"Name=%@, Count=%lu", item, (unsigned long)[set countForObject:item]);
}
like image 34
Jakub Truhlář Avatar answered Oct 12 '22 18:10

Jakub Truhlář