What is the most efficient way to get the count of the unique values on a table?
For example:
fruitType
---------
banana
banana
apple
apple
apple
bananas : 2
apples : 3
By using fruitsCollection.distinct(by: ["fruitType"])
i can get the distinct values but not the count.
Any help would be appreciated.
2
Answers
you could try something simple like this (assuming fruits are Strings, adjust accordingly to your object types):
or
The
Set(fruits)
gives you the unique set offruit
names. Thefilter{...}
gives you the count of each. TheforEach
or thereduce
turns the results into a dictionary of key values.@workingdog answer works very well but here’s a more Realmy option. Something to keep in mind is that Realm Results objects are lazily loaded – meaning working with very large datasets has a low memory impact.
However, as soon high level Swift functions are used, that lazy-ness is lost and every object gobbles up memory.
For example, loading 50,000 Realm objects into a Results object doesn’t have any significant memory impact – however, loading 50,000 objects into an Array could overwhelm the device as the objects loose their lazy-loading nature.
With this solution, we rely on Realm to present unique values and store them in Results (lazy!) then iterating over those we filter for matching objects (lazy) and return their count.
I created a FruitClass to hold the fruit types
and then to code
and the results