0

I have a NSMutableArray and say i have a 'days' column in there and the data contained in there ranges from 0-4 say i have 5 rows like so

0
0
1
2
3

i want to count how many unique items there is so in this case it would return 4 as it wouldnt count the second 0.

Thanks for your help

4
  • What do you mean with having a days column in an array? Are the objects in the array objects with a 'day' property? Commented Feb 13, 2013 at 22:01
  • Define "unique". You could (in theory, though not in practice) have two different NSNumber objects with the value zero. Commented Feb 13, 2013 at 22:12
  • 1
    NSUInteger count = [[yourOriginalArray valueForKeyPath:@"@distinctUnionOfObjects.day"] count]; Commented Feb 13, 2013 at 23:04
  • @holex solution is perfect Commented May 30, 2013 at 18:41

3 Answers 3

1

How about [NSSet setWithArray:yourArray].count.

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

Comments

0

It is straight forward. What you want to do is remove duplicate item in array and get count of unique item. This can be done by using NSSet and NSMutableArray:

[uniqueArray addObjectsFromArray:[[NSSet setWithArray:duplicateArray] allObjects]];
[uniqueArray count];

Hope this help

Comments

0

If your array is already sorted, you could make a single pass through it, maintaining a variable containing the 'current' value, and a counter, that is incremented every time the current value doesn't match the one at the index (and then updating the 'current' value to match. This takes slightly more lines of code than the above, but is substantially faster if the array is large enough that building a set from all the array elements is a big enough task to matter performance-wise.

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.