How to get min or max of an array in JavaScript

max function of Math object

The Math.max() function returns the largest of zero or more numbers.

and min function of Math object

The Math.min() function returns the smallest of zero or more numbers.

Example of using max or min functions

Math.max(1, 2, 3) // 3Math.min(1, 2, 3) // 1

But what if we have array of number and we would like to find min and max value in it. If we send an array to Math.min or Math.max methods we will get NaN

const nums = [1, 2, 3]Math.min(nums) // NaNMath.max(nums) // Nan

That is because Math.min or Math.max functions expect distinct variables and not an array. So in order to do that before ES6/ES2015 apply method was used

var nums = [1, 2, 3]Math.min.apply(Math, nums) // 1Math.max.apply(Math, nums) // 3Math.min.apply(null, nums) // 1Math.max.apply(null, nums) // 3

With ES6/ES2016 destructuring assignment it becomes easier

The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables.

const nums = [1, 2, 3]Math.min(…nums) // 1Math.max(…nums) // 3

? in front of an array will convert array to distinct variables and send them to the function, which is equivalent to

Math.min(1, 2, 3)Math.max(1, 2, 3)

4

No Responses

Write a response