4

How to remove duplicates from a list with lists in Dart / Flutter?

.toSet().toList() doesn't work.

For Example:

List one = [
     [
        [6, 51],
        [2, 76]
     ],
     [
        [6, 51],
        [2, 76]
     ],
     [
        [5, 66],
        [4, 96]
     ]
]

Would be:

List two = [
     [
        [6, 51],
        [2, 76]
     ],
     [
        [5, 66],
        [4, 96]
     ]
]
Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
Sem
  • 45
  • 6

3 Answers3

3

I hope this works. Also import 'dart:convert';

List two = 
  one.map((f) => f.toString()).toSet().toList()
  .map((f) => json.decode(f) as List<dynamic>).toList();
MJ Montes
  • 3,234
  • 1
  • 19
  • 21
0

You can take advantage of properties of Set.

List two = one.toSet().toList();
OldJii
  • 1
-1

Not incredibly efficient, but this could work

void main() {
  List<List<List<int>>> one = [
    [
      [6, 51],
      [2, 76]
    ],
    [
      [6, 51],
      [2, 76]
    ],
    [
      [5, 66],
      [4, 96]
    ]
  ];

  print(one);

  print(one.removeDuplicates());
}

extension ListExtension<T> on List<T> {
  bool _containsElement(T e) {
    for (T element in this) {
      if (element.toString().compareTo(e.toString()) == 0) return true;
    }
    return false;
  }

  List<T> removeDuplicates() {
    List<T> tempList = [];

    this.forEach((element) {
      if (!tempList._containsElement(element)) tempList.add(element);
    });
    
    return tempList;
  }
}

Ajil O.
  • 6,562
  • 5
  • 40
  • 72