Merge two lists of objects in Dart

Viewed 692

I have objects which have a parameter name and a parameter counter. Those objects are stores inside a list. Some of the items in my list have the duplicate parameter "name". I want to remove the duplicates inside the list and add the counter of that duplicate to the duplicate-objects parameter.

class Person{ 
Person({this.name, this.counter)};
  String name;
  int counter;
}

List<Person> theList = [];

theList.add(Person(name:"Ben", counter: 2);
theList.add(Person(name:"Ben", counter: 5);

//I need a function that changes the List to show Ben with counter 7
2 Answers
class Person{ 
  final String name;
  int counter;
  Person({required this.name, required this.counter});
}

extension on List<Person> {
  void addPerson({required String name, required int counter}) {
    if (isNotEmpty) {
      try {
        var person = firstWhere((p) => p.name == name);
        person.counter += counter;
      } catch(e) { 
        add(Person(name:name, counter: counter));
      }
    } else {
      add(Person(name:name, counter: counter));
    }
  }
}

void main() {
  var theList = <Person>[];

  theList.addPerson(name:"Lucho", counter: 4);
  theList.addPerson(name:"Ben", counter: 2);
  theList.addPerson(name:"Ben", counter: 5);  
  
  print(theList);
  print(theList.length);
  print("${theList[1].name} - ${theList[1].counter}");  
}

Result:

[Instance of 'Person', Instance of 'Person']
2
Ben - 7

first define a class for a list of Persons:

class PersonList{
  List<Person> _personList = [];

  get personList{
    return [..._personList];
  }

  void addToList(Person person){
    for(int i=0; i<_personList.length; i++){
      if(_personList[i].name == person.name){
        _personList[i].counter = _personList[i].counter + person.counter;
        return;
      }
    }
    _personList.add(person);
    return;
  }
}

then, you can create a new instance of it and add some entries to the list:

PersonList theList = new PersonList();
theList.addToList(Person(name:"Ben", counter: 2));
    print(theList.personList[0].counter);
    theList.addToList(Person(name:"Ben", counter: 5));
    print(theList.personList[0].counter);

feel free to only use the addToList method.

Related