distinctBy method

List<T> distinctBy(
  1. dynamic predicate(
    1. T selector
    )
)

Returns a list containing only the elements from given collection having distinct keys.

Basically it's just like distinct function but with a predicate example: User(22, "Sasha"), User(23, "Mika"), User(23, "Miryam"), User(30, "Josh"), User(36, "Ran"), .distinctBy((u) => u.age).forEach((user) { print("${user.age} ${user.name}"); });

result: 22 Sasha 23 Mika 30 Josh 36 Ran

Implementation

List<T> distinctBy(predicate(T selector)) {
  final set = HashSet();
  final List<T> list = [];
  toList().forEach((e) {
    final key = predicate(e);
    if (set.add(key)) {
      list.add(e);
    }
  });

  return list;
}