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!
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.
//Number of elements present in an array can be calculated as follows. int length = sizeof(arr)/sizeof(arr[0]);
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.
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.
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);
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]; ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With