distinctBy<K> method

Set<E> distinctBy<K>(
  1. K key(
    1. E element
    )
)

Returns a new set with duplicates removed based on the given key function.

Example:

final set = {'apple', 'banana', 'avocado'};
print(set.distinctBy((e) => e[0])); // {apple, banana}

Implementation

Set<E> distinctBy<K>(K Function(E element) key) {
  final result = <E>{};
  final keys = <K>{};
  for (final element in this) {
    final k = key(element);
    if (keys.add(k)) {
      result.add(element);
    }
  }
  return result;
}