0

I have a dart list:

List<Car> cars = new List<Car>();

//Car(brand, quantity)

Car car = new Car ("nissan", 2);
cars.add(car);

car = new Car("nissan", 4);
cars.add(car);

car = new Car("toyota", 3);
cars.add(car);

car = new Car("nissan", 5);
cars.add(car);

car = new Car("toyota", 2);
cars.add(car);

How can i get a list of Cars which should only contains 2 records (which is the sum of the quantity):

Car("nissan", 11)
Car("toyota", 5)
Steven
  • 1,996
  • 3
  • 22
  • 33
Aexperty
  • 21
  • 1
  • 1
    quiz time!!! Seriously, StackOverflow expect you to have some kind of codes that you've tried before throwing us the problem... Btw, welcome to StackOverflow. Please read our guidelines https://stackoverflow.com/help/on-topic. – ariefbayu Mar 09 '20 at 07:48
  • so what have you tried? – pskink Mar 09 '20 at 07:52
  • The values `Car("nissan", 11)` or `Car("toyota", 5)` don't exist in your cars list, so this cannot be answerred. – Steven Mar 09 '20 at 07:54
  • @Steven but if you group car makers add sum the quantity... – pskink Mar 09 '20 at 07:55
  • In that case, there's a solid question in here if it's worded correctly. I've edited it. – Steven Mar 09 '20 at 07:58

1 Answers1

1

You can use a map literal and then count using a forEach loop.

  var carMap = {};
  cars.forEach((car) {
    String key = car.brand;
    if (carMap.containsKey(key)) {
      carMap[key] += car.quantity;
    } else {
      carMap[key] = car.quantity;
    }
  });
  print(carMap);
Manish
  • 4,903
  • 1
  • 29
  • 39
  • better use `groupBy` top level function in that case – pskink Mar 09 '20 at 08:01
  • How can i use groupBy in this situation? – Aexperty Mar 09 '20 at 08:31
  • @Manish many thanks for your answer, ..actually i have more attribute in this list (ex. Maker, quantity, description) and wanted to sum quantity by maker and return it as “List”... ? – Aexperty Mar 09 '20 at 08:31
  • @Aexperty this should guide you: https://stackoverflow.com/questions/54029370/flutter-dart-how-to-groupby-list-of-maps/54036449 – ariefbayu Mar 09 '20 at 08:33
  • @Aexperty How does description get reduced i.e. How does the `description` in different objects gets combined; like sum, append, take first etc? – Manish Mar 09 '20 at 08:53
  • @manish ... let us take it with another example like "category" ... it is a more clear example of the case ... category for all nissan records are same "nissanCategory", and for all toyota also same "toyotaCategory". – Aexperty Mar 09 '20 at 11:54
  • @Manish .. appreciate if you can guide in this regard – Aexperty Mar 10 '20 at 15:16
  • @ariefbayu here OP is showing a List with properties. He is not stating this coming straight from a JSON fetch. – MwBakker Jun 24 '22 at 10:24