Home > Mobile >  How to achieve this logic of 'summing up values of map keys inside a list'
How to achieve this logic of 'summing up values of map keys inside a list'

Time:03-10

  • I have a list of Map<String, int>, let's call it salesData.
  • Each element inside this list represents a sale.
  • Each sale may have products that may or may not exist in other sales.

Note: this data comes from some api, therefore the products' name aren't known!

    List<Map<String, int>> salesData = [
    {'product A': 12, 'product B': 30, 'product C': 17, 'product K': 220},
    {'product A': 3, 'product F': 2, 'product C': 10},
    {'product F': 6, 'product S': 4, 'product A': 1},
    {'product F': 1, 'product S': 11,},
  ];

My goal is to get an instance of each product and the summed up totals from all the sales. for example the totals of product A is 16, B is 30, so on.

Things I have tried:

Map<String, int> finalSaleData = {};

Set<String> mySet = {};

for (var element in salesData) {
      mySet.addAll(element.keys);
    }

for (var productName in mySet) {
    finalSaleData[productName] = salesData.fold(0, (previousValue, e) => previousValue   e[element]); 
   // this line works as long as the e[element] exists, but not if it doesn't!
    }

CodePudding user response:

final result = salesData.reduce((sum, item) =>
  {...sum, ...item.map((key, value) =>
    MapEntry(key, (sum[key] ?? 0)   value)
  )}
);

CodePudding user response:

Map summingItUp = Map();
for (Map item in salesData) {
  item.forEach((key, value) {
    if (summingItUp.containsKey(key))
      summingItUp[key] = summingItUp[key]   value;
    else
      summingItUp[key] = value;
  });
}
print(summingItUp);

the result would be:

{product A: 16, product B: 30, product C: 27, product K: 220, product F: 9, product S: 15}
  • Related