Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: Count the number of times an object occurs in an array?

I need to perform what I feel is a basic function but I can't find any documentation on how to do it. Please help!

I need to count how many times a certain object occurs in an array. See example:

array = NSArray arrayWithObjects:@"Apple", @"Banana", @"Cantaloupe", @"Apple", @"DragonFruit", @"Eggplant", @"Apple", @"Apple", @"Guava",nil]retain];

How can I iterate through the array and count the number of times it finds the string @"Apple"?

Any help is appreciated!

like image 894
EmphaticArmPump Avatar asked Jan 28 '11 23:01

EmphaticArmPump


People also ask

How do you count the number of times an element appears in an array?

The frequency of an element can be counted using two loops. One loop will be used to select an element from an array, and another loop will be used to compare the selected element with the rest of the array. Initialize count to 1 in the first loop to maintain a count of each element.

How do you count the number of terms in an array?

//Number of elements present in an array can be calculated as follows. int length = sizeof(arr)/sizeof(arr[0]);

Which method is used for counting of array element?

You can count the total number of elements or some specific elements in the array using an extension method Count() method. The Count() method is an extension method of IEnumerable included in System.

How do you count occurrences of an element in a swift array?

In the Swift array, we can count the elements of the array. To do this we use the count property of the array. This property is used to count the total number of values available in the specified array.


2 Answers

One more solution, using blocks (working example):

NSInteger occurrences = [[array indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {return [obj isEqual:@"Apple"];}] count];
NSLog(@"%d",occurrences);
like image 77
Martin Babacaev Avatar answered Oct 07 '22 11:10

Martin Babacaev


As @bbum said, use an NSCounted set. There is an initializer thet will convert an array directly into a counted set:

    NSArray *array = [[NSArray alloc] initWithObjects:@"A", @"B", @"X", @"B", @"C", @"D", @"B", @"E", @"M", @"X", nil];
    NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:array];
    NSLog(@"%@", countedSet);

NSLog output: (D [1], M [1], E [1], A [1], B [3], X [2], C [1])

Just access items:

count = [countedSet countForObject: anObj]; ...
like image 45
zaph Avatar answered Oct 07 '22 11:10

zaph