Get the Min/Max elements of an Array in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 08 20212 min read

banner

Photo by trail

Get the Min/Max elements of an Array in JavaScript #

To get the min and max elements of an array, call the Math.min() and Math.max() methods alongside the spread operator. E.g. Math.min(...arr) returns the min element, whereas Math.max(...arr) returns the max element of the array.

index.js
// Not Supported in IE 6-11 const arr = [5, 10, 15, 3, 6, 9]; const min = Math.min(...arr); console.log(min); // ๐Ÿ‘‰๏ธ 3 const max = Math.max(...arr); console.log(max); // ๐Ÿ‘‰๏ธ 15

The Math.min and Math.max methods take comma separated numbers as parameters.

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

Since we can't pass an array to the methods we use the spread operator.

An easy way to think about it is - we are unpacking the values from the array and passing them as comma separated values into the Math.min and Math.max methods.

The spread operator is not supported in Internet Explorer versions 6-11. If you have to support the browser, you can either use babel to compile your code to an older version of JavaScript or use the next approach in the article.

If you need to support Internet Explorer, use the Function.apply method instead of the spread operator.

To get the min and max elements of an array, call the apply method on both Math.min and Math.max, passing it null as the first parameter and the array as the second. The apply method will unpack the array in the call to the Math.min and Math.max methods.

index.js
// Supported in IE 6-11 const arr = [5, 10, 15, 3, 6, 9]; const min = Math.min.apply(null, arr); console.log(min); // ๐Ÿ‘‰๏ธ 3 const max = Math.max.apply(null, arr); console.log(max); // ๐Ÿ‘‰๏ธ 15

The 2 arguments we passed to the Function.apply method are:

  1. the this argument - for our purposes it is irrelevant
  2. an array containing the arguments that will be provided to the Math.min and Math.max functions.
Under the hood the Function.apply method unpacks the elements of the array and passes them as comma separated arguments to the function.

This approach is a little less intuitive and readable than the first one, however if you have to support Internet Explorer, it gets the job done.

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