Get the Min/Max Values in a Set in JavaScript

avatar

Borislav Hadzhiev

Sat Nov 06 20211 min read

Get the Min/Max Values in a Set #

To get the min and max values in a Set, use the spread syntax (...) to pass the Set to the Math.min() and Math.max() methods. The Math.min and Math.max methods return the lowest and highest of the passed in numbers.

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

A Set is an iterator object, just like an array.

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(1, 3, 5); console.log(min); // ๐Ÿ‘‰๏ธ 1 const max = Math.max(1, 3, 5); console.log(max); // ๐Ÿ‘‰๏ธ 5

To unpack the values from the Set 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 Set and passes them 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