1

I have a Map which is filled with entries and I would like to sum the values. The problem is: reduce() only seems to work for arrays, while map.values() returns an iterator.

Is there some easy way to do this or is some external library required?

helpermethod
  • 59,493
  • 71
  • 188
  • 276

2 Answers2

2

There don't yet exist utility methods on the iterator interface, but you can trivially fold using a for of loop:

let sum = 0;
for (const value of myMap.values())
    sum += value;
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

You can do it like this:

var sum = 0;
myMap.forEach((value, key)=> sum+=value);
jonasnas
  • 3,540
  • 1
  • 23
  • 32