Get the Min/Max elements of an Array in JavaScript

Borislav Hadzhiev

Fri Oct 08 2021ยท2 min read

Photo by trail

**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

Copied!`// 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

Copied!`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

Copied!`// 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:

- the
`this`

argument - for our purposes it is irrelevant - 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.

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