How to delete duplicates in a dart List? list.distinct()?

Use toSet and then toList

  var ids = [1, 4, 4, 4, 5, 6, 6];
  var distinctIds = ids.toSet().toList();

Result: [1, 4, 5, 6]

Or with spread operators:

var distinctIds = [...{...ids}];

Set works okay, but it doesn't preserve the order. Here's another way using LinkedHashSet:

import "dart:collection";

void main() {
  List<String> arr = ["a", "a", "b", "c", "b", "d"];
  List<String> result = LinkedHashSet<String>.from(arr).toList();
  print(result); // => ["a", "b", "c", "d"]
}

https://api.dart.dev/stable/2.4.0/dart-collection/LinkedHashSet/LinkedHashSet.from.html


I didn't find any of the provided answers very helpful. Here is what I generally do:

    final ids = myList.map((e) => e.id).toSet();
    myList.retainWhere((x) => ids.remove(x.id));

Of course you can use any attribute which uniquely identifies your objects, it doesn't have to be an id field.

This approach is particularly useful for richer objects. For simple primitive types some of the answers already posted here are fine. Another nice side-effect of this solution is that unlike others provided here, this solution does not change the order of your original items in the list as it modifies the list in place!

Tags:

List

Dart