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

后端 未结 11 2049
夕颜
夕颜 2020-12-01 05:21

How do i delete duplicates from a list without fooling around with a set? Is there something like list.distinct()? or list.unique()?

void main() {
  print(\"         


        
相关标签:
11条回答
  • 2020-12-01 05:35

    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}];
    
    0 讨论(0)
  • 2020-12-01 05:39

    try the following

    List<String> duplicates = ["a","c","a"];
    
    duplicates = duplicates.toSet().toList();
    

    check the Dartpad link - https://dartpad.dev/4d3a724429bbd605f4682b7da253a16e

    0 讨论(0)
  • 2020-12-01 05:42

    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

    0 讨论(0)
  • 2020-12-01 05:42
    void uniqifyList(List<Dynamic> list) {
      for (int i = 0; i < list.length; i++) {
        Dynamic o = list[i];
        int index;
        // Remove duplicates
        do {
          index = list.indexOf(o, i+1);
          if (index != -1) {
            list.removeRange(index, 1);
          }
        } while (index != -1);
      }
    }
    
    void main() {
      List<String> list = ['abc', "abc", 'def'];
      print('$list');
      uniqifyList(list);
      print('$list');
    }
    

    Gives output:

    [abc, abc, def]
    [abc, def]
    
    0 讨论(0)
  • 2020-12-01 05:43

    Using dart 2.3+, you can use the spread operators to do this:

    final ids = [1, 4, 4, 4, 5, 6, 6]; 
    final distinctIds = [...{...ids}];
    

    Whether this is more or less readable than ids.toSet().toList() I'll let the reader decide :)

    0 讨论(0)
提交回复
热议问题