Dart/Flutter: How can i calculate values of multiple maps which contains same key?

Viewed 401

I am new to Dart and i got stuck at this point for days.

I have multiple maps and these maps follow the same pattern (date:value) but their lengths are different. And these maps are increased dynamically.

For example:

Map1:{01.01.2021:2,02.01.2021:5,03.01.2021:3}, 
Map2:{02.01.2021:10,03.01.2021:4,04.01.2021:8}, 
Map3...
Map4...
...

I want to combine these maps and sum the values that contains the same key and store it in an another map. For the different keys, there will be no calculation and store as it is.

Result for Map1 & Map2:

Combined Map{01.01.2021:2,02.01.2021:(5+3),03.01.2021:(3+4),04.01.2021:8}

How can i perform such an operation considering that these maps are iterable inside a class or inside an another list.

Thank you in advance.

1 Answers

Here you go! Paste this on DartPad

This will work with any number of maps inside data map

Any questions fell free to ask me in the comments.

void main() {
  
  final data = {
    'Map1': {'01.01.2021':2,'02.01.2021':5,'03.01.2021':3}, 
    'Map2': {'02.01.2021':10,'03.01.2021':4,'04.01.2021':8}, 
  };

  final finalData = {};
  
  for(final key in data.keys) {
    for(final date in data[key]!.keys) {
      final initialValue = finalData[date];
      
      if(initialValue == null) {
        finalData[date] = data[key]![date];
      } else {
        finalData[date] = initialValue + data[key]![date];
      }
    }
  }
  // {01.01.2021: 2, 02.01.2021: 15, 03.01.2021: 7, 04.01.2021: 8}
  print(finalData);
}

The inner loop can be written more succinctly using the tertiary operator

for (final date in data[key]!.keys) {
  final initialValue = finalData[date];
  finalData[date] = initialValue == null
      ? data[key]![date]
      : initialValue + data[key]![date];
}

or the null aware operator (??)

for (final date in data[key]!.keys) {
  finalData[date] = data[key]![date]! + (finalData[date] ?? 0);
}
Related