How to count duplicate values ​​in NSArray?

The value of my NSArray includes duplicates. I find duplicates, but now how can I find no. are they repeated

+7
source share
3 answers

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

+35
source

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]); } 
+8
source

You can try something like this

 __block NSInteger elementCount = 0; NSArray *array; [<#NSArray yourArray#> indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop){ if (obj == <#yourObject#>) { elementCount++; return YES; } return NO; }]; 

Let me know if this works for you.

+1
source

All Articles