distinct method

List<T> distinct([
  1. Object key(
    1. T element
    )?
])

Deletes duplicate elements in an array.

By setting the return value of key to a specific duplicate key, duplicate checking can be performed for each specified duplicate key.

配列の中の重複している要素を削除します。

keyの返り値を特定の重複キーにすることで指定された重複キーごとに重複チェックを行うことが可能です。

final array = [1, 1, 3, 5, 6, 8, 9, 9];
final distinct = array.distinct(); // [1, 3, 5, 6, 8, 9]

Implementation

List<T> distinct([Object Function(T element)? key]) {
  if (key == null) {
    return toSet().toList();
  }
  final tmp = <Object, T>{};
  for (final element in this) {
    final o = key.call(element);
    if (tmp.containsKey(o)) {
      continue;
    }
    tmp[o] = element;
  }
  return tmp.values.toList();
}