Reputation: 79
I have a Map<String, Map<String, double>> myMap = ...
and I would like to sum all the values in the second map. I have managed to do it like this
double sum = 0;
myMap.entries.forEach((element) {
Map<String, double> map = element.value;
sum += map.entries.map((e) => e.value).toList().fold(0, (a, b) => a + b);
});
Is it possible to sum it using only one line without .forEach()
?
Upvotes: 1
Views: 1007
Reputation:
ok, then an another option:
var sum = myMap.values.expand((e) => e.values).fold(0, (a, b) => a + b);
Upvotes: 2
Reputation: 79
I've managed to come up with the solution that works and all in one line.
double sum = myMap.values
.map((e) => e.values)
.fold(0, (a, b) => a + b.fold(0, (a, b) => a + b));
Upvotes: 0
Reputation: 246
Try this one liner:
num sum = 0;
map.forEach((k, v) => v.forEach((kk, vv) => sum += vv));
Upvotes: 1