distinctBy<E> method

Set<T> distinctBy<E>(
  1. E predicate(
    1. T
    )
)

Removes duplicate elements from a list based on a provided predicate.

The predicate function should return a value that uniquely identifies each element. Elements with the same value returned by the predicate are considered duplicates and only the first occurrence is retained.

Example usage:

void main() {
  List<Map<String, dynamic>> inputList = [
    {'id': 1, 'name': 'Alice'},
    {'id': 2, 'name': 'Bob'},
    {'id': 1, 'name': 'Charlie'},
    {'id': 3, 'name': 'David'},
  ];

  // Distinct by 'id'
  List<Map<String, dynamic>> result = distinctBy(inputList, (element) => element['id']);
  print(result);  // Output: [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'David'}]
}

Implementation

Set<T> distinctBy<E>(E Function(T) predicate) {
  Set<T> uniqueElements = {};
  for (T element in this) {
    if (!uniqueElements.any((e) => predicate(e) == predicate(element))) {
      uniqueElements.add(element);
    }
  }
  return uniqueElements;
}