Count number of occurrences of an item in an array in Swift
In this tutorial, we will discuss how to count the number of occurrences of an item in an array in Swift. It simply means to show the number of occurrences of any element in an array.
It is obvious that we can do this in multiple ways. Here we go-
Method 1: using loop
In this method, we will be given an array of elements, say strings or integers, and we need to find the number of times a particular element occurred. This can be helpful in a large dataset where we need to find the number of students who got A+ in a particular subject and there are many real-life examples.
We will be using reduce the function of the array and dictionary’s subscript(default) which will reduce the array into a dictionary where the count will store the count of the elements and i
will loop the dictionary and by default, the count is one and we will increase the count if the element is found.
let arr = [16,8,7,16,7,89] let dict = arr.reduce(into: [:]) { count, i in count[i, default: 0] += 1 } print(dict)
[7: 2, 16: 2, 89: 1, 8: 1]
Method 2: using grouping
In this method, we will look forward to another method that creates a dictionary of the array values and then groups the array by shorthand $0 which means the first argument, and then we will map the values into the newd
which is a new dictionary and then return the mapped value, printing the newd
.
let arr = [7,2,2,71,7,23] let dict = Dictionary(grouping: arr, by: { $0 }) let newd = dict.mapValues { (i: [Int]) in return i.count } print(newd)
[71: 1, 2: 2, 7: 2, 23: 1]
Method 3: using map()
This method would take into the use of map() which maps the key and value after a dictionary is created of the given values of the array. It is similar to the above method which creates a new array instead of a dictionary. Here’s the code-
let arr = [7,2,2,71,7,23] let dict = Dictionary(grouping: arr, by: { $0 }) let newArr = dict.map { (key: Int, value: [Int]) in return (key, value.count) } print(newArr)
[(7, 2), (23, 1), (71, 1), (2, 2)]
So here we have discussed 3 methods of how to print the total count of elements in a given array with the number of their occurrence. I hope you find this article helpful.
Leave a Reply