listflutterdart

Dart - find duplicate values on a List


how can I find duplicate values on a list, Let's say I got a List like this:

List<Map<String, dynamic>> users = [
    { "name": 'John', 'age': 18 },
    { "name": 'Jane', 'age': 21 },
    { "name": 'Mary', 'age': 23 },
    { "name": 'Mary', 'age': 27 },
  ];

How I can iterate the list to know if there are users with the same name?


Solution

  • A simple way would be this:

    void main() {
      List<Map<String, dynamic>> users = [
        { "name": 'John', 'age': 18 },
        { "name": 'Jane', 'age': 21 },
        { "name": 'Mary', 'age': 23 },
        { "name": 'Mary', 'age': 27 },
      ];
      List names = []; // List();
      users.forEach((u){
        if (names.contains(u["name"])) print("duplicate ${u["name"]}");
        else names.add(u["name"]);
      });
    }
    

    Result:

    duplicate Mary