Get the Min/Max Values in a Map in JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 6, 2021

banner

Photo from Unsplash

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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.