8

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

3
  • How are you finding the duplicates? If you're stepping through the array values and comparing them, you should be able to incriment an int whenever you hit a duplicate value. Commented Jul 27, 2011 at 7:53
  • NSArray *cleanedArray = [[NSSet setWithArray:duplicateElements] allObjects]; By this code I remove duplicates. Commented Jul 27, 2011 at 9:24
  • Yeah, I don't think you're going to be able to get a count out of that method. Look at @omz suggestion, it seems like it's going to work a treat. Then you can call the [[NSSet setWithArray:duplicateElements] allObjects]; methods. Commented Jul 27, 2011 at 11:09

3 Answers 3

37

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually, I'll just +1 this answer and bookmark it in Chrome.
9

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

Comments

1

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 that works for you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.