Get the Min/Max Values in a Map in JavaScript

avatar

Borislav Hadzhiev

Sat Nov 06 20211 min read

banner

Photo by Nyana Stoica

Get the Min/Max Values in a Map #

To get the min and max values in a Map:

  1. Use the values() method to get an iterator object of the Map's values.
  2. Using spread syntax, pass the iterator to the Math.min() and Math.max() methods.
  3. The Math.min and Math.max methods return the lowest and highest of the passed in numbers.
index.js
const map1 = new Map([ ['num1', 3], ['num2', 5], ['num3', 8], ]); const min = Math.min(...map1.values()); console.log(min); // ๐Ÿ‘‰๏ธ 3 const max = Math.max(...map1.values()); console.log(max); // ๐Ÿ‘‰๏ธ 8

We used the Map.values method to get an iterator object containing the Map's values.

We can't pass the iterator object directly to the Math.max and Math.min methods, because they expect multiple, comma-separated numbers and not an iterator.

index.js
const min = Math.min(3, 5, 8); console.log(min); // ๐Ÿ‘‰๏ธ 3 const max = Math.max(3, 5, 8); console.log(max); // ๐Ÿ‘‰๏ธ 8

To unpack the values from the iterator object in the calls to the Math.min() and Math.max() methods, we used the spread syntax (...).

You can imagine that the spread syntax passes the values from the iterator object as comma-separated parameters to the methods.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee