8

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,        
  };
0

1 Answer 1

15

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

Sign up to request clarification or add additional context in comments.

1 Comment

Its correct... But please consider .fold() as it can be used in more cases than .reduce(). Also its safer with list that might present an empty value from a returning http call

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.