Borislav Hadzhiev
Sat Nov 06 2021·1 min read
Photo by Nyana Stoica
To get the min and max values in a Map:
values()
method to get an iterator object of the Map's values.Math.min()
and Math.max()
methods.Math.min
and Math.max
methods return the lowest and highest of the
passed in numbers.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.
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.