0

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
  • 55,449
  • 64
  • 175
  • 266

2 Answers2

1

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
  • 572,313
  • 128
  • 898
  • 1,281
1

You can do it like this:

var sum = 0;
myMap.forEach((value, key)=> sum+=value);
jonasnas
  • 3,510
  • 1
  • 21
  • 31