Reputation: 1941
Basically I need a function which counts the amount of different values in an array and one other function to give me the actual count of each different value in my array.
I have an Array which contains a changing amount of values:
Array = (This, This, This, This, Is, Is, Is, Is, Is, It, It, It, It)
I want to make a list view, each section should contain the different categories like:
This
- Element 1
- Element 2
- ...
Is
- Element 1
- ...
It
- Element 1
- ...
So I need the number 3 for my number of sections and the number of child-elements for each section.
How can I achieve that? Is there a better way than a for-statement with counting indexes for each section?
Thank you!
Upvotes: 0
Views: 92
Reputation: 2022
First, make o copy of your array, to work with.
To get the actual count of each group: you have the copied array already without duplicates, so make a for loop within the copied array:
for (NSString *stringer in copiedArrayWithoutDuplicates){
int counter = 0;
for(NSString *iniStr in initialArrayWithDuplicates){
if([stringer isEqualToString: iniStr]){
counter++;
}
}
NSLog(@"string %@ was detected %i times", stringer, counter);
}
Upvotes: 0
Reputation: 385870
Add each array element to an NSCountedSet
. Then the count
of the set is the number of distinct objects you added, and you can use countForObject:
to ask the set how many there are of each distinct object.
Upvotes: 4