Reputation: 1
I have a map of items and its prices, I want to sum some selected(not all) values of keys how? in dart I have tried all values except one but cant do other than this. my map contains string key and double value
Upvotes: 0
Views: 816
Reputation: 1545
In general, you want to perform a filter-map-reduce
operation here - filter
to get all elements which have a certain property, map
to extract the value from each element, and finally reduce
to aggregate the results to a single value (the sum, in this case).
An example in Dart could look something like this:
final Map<String, int> map = {
"item": 10,
"anotherItem": 20,
"yetAnotherItem": 30
};
final sumOfEvenLengthKeys = map.entries
.where((e) => e.key.length % 2 == 0)
.map((e) => e.value)
.reduce((a, b) => a + b);
Which would produce 40
.
Upvotes: 1