Skip to content

How can you reduce(…) the entries of a JavaScript Map object without expanding to a list?

It seems there’s no good standard library way of doing something like this?

let thismap = new Map([[1,2],[2,3]])
console.log(thismap.entries().reduce((prev, [a,b])=>prev + a * b, 0))

Uncaught TypeError: thismap.entries(...).reduce is not a function

I assume this is due to the entries() function returning an iterator? I don’t want to Array.from(thismap.entries()).reduce(...), as that would unnecessarily build the array in memory. It feels like I’m missing something, but I also don’t want to reimplement something that should be in the standard library.

I suppose if I was using an object instead (not a satisfactory solution here for other reasons), the entries() would essentially be an array expansion instead of an iterator (although I suppose it could be implemented with memory efficiency in mind). But still, I’d want to know how to reduce an iterator

Answer

I also don’t want to reimplement something that should be in the standard library.

It really should indeed. There’s a proposal to add it: Iterator Helpers. While waiting for it, you can already use the polyfill which will make your original code work 🙂