mode<T> function
Summarizing data
Returns the mode of all values in the iterable, i.e., the value which
appears the most often.
The mode is determined based on the frequency of occurrences using the Object.== to compare values. In case of equality, returns the first of the relevant values.
This function ignores values that do not satisfy any of the following conditions:
- The value is not
null. - The value is not a special case like double.nan, which does not satisfy self-equality according to Object.==.
Useful for filtering and ignoring missing data in datasets.
If the iterable is empty or contains no valid values, this function
returns null.
Implementation
T? mode<T>(Iterable<T> iterable) {
Map<T, int> counts = {};
for (final value in iterable) {
if (value != null && value == value) {
counts[value] = (counts[value] ?? 0) + 1;
}
}
T? modeValue;
var modeCount = 0;
for (final MapEntry(key: value, value: count) in counts.entries) {
if (count > modeCount) {
modeCount = count;
modeValue = value;
}
}
return modeValue;
}