How do you count the amount of unique items in an Array?
Example:
let array:Array<Int> = [1,3,2,4,6,1,3,2]
Count function:
array.count
will give 8
but I want to count unique items and this will give 5
How do you count the amount of unique items in an Array?
Example:
let array:Array<Int> = [1,3,2,4,6,1,3,2]
Count function:
array.count
will give 8
but I want to count unique items and this will give 5
If you prefer to stick with pure swift, a possible solution consists of:
Translated in code:
the result is stored in the element 0 of the
count
tuple.Explanation: the
start
tuple is initialized with0
andnil
, and passed as the initial value to thereduce
method, called on a sorted copy of the array. At each iteration, a new tuple is returned, containing the current array element and the current counter, increased by one if the current element is different than the previous one.You can use NSSet to throw away duplicates:
This prints:
As of Swift 1.2, Swift has a native
Set
type. Use theSet
constructor to create a set from your array, and then thecount
property will tell you how many unique items you have:For Swift 1.1 and earlier:
Turn your array into an
NSSet
:You can read more about it here.
If you are interested in how many of each item you have, you can use a dictionary to count the items: