distinctBy<K> method

Iterable<T> distinctBy<K>(
  1. K key(
    1. T
    )
)

Returns a new iterable containing only elements that are distinct by the value returned by key.

The first occurrence of each distinct key is kept; later duplicates are dropped.

final users = [('Alice', 1), ('Bob', 2), ('AliceB', 1)];
users.distinctBy((u) => u.$2);  // [('Alice', 1), ('Bob', 2)]

Implementation

Iterable<T> distinctBy<K>(K Function(T) key) sync* {
  final seen = <K>{};
  for (final element in this) {
    if (seen.add(key(element))) {
      yield element;
    }
  }
}