Peter aziz
Peter aziz

Reputation: 150

Adding all the values in a map in dart

How to add all the values of a map to have the total of 14000?

Map<String, int> salary = {
    "user1": 4000,
    "user2": 4000,
    "user3": 3000,
    "user4": 3000,        
  };

Upvotes: 8

Views: 11944

Answers (1)

yelliver
yelliver

Reputation: 5926

Firstly, you just care about the values of this map, not care about the keys, so we work on the values by this:

var values = salary.values;

And we can use reduce to combine all the values with sum operator:

var values = salary.values;
var result = values.reduce((sum, element) => sum + element);
print(result);

You can reference some basic of List & Map here:

https://api.dartlang.org/stable/1.10.1/dart-core/List-class.html https://api.dartlang.org/stable/1.10.1/dart-core/Map-class.html

Upvotes: 15

Related Questions