# The Fastest Way to Find Minimum and Maximum Values in an Array in JavaScript

## Setup

``````// randomly generated N = 40 length array 0 <= A[N] <= 39
const array = Array.from({length: 40}, () => Math.floor(Math.random() * 40))

// randomly generated N = 4000 length array 0 <= A[N] <= 3999
// const array = Array.from({length: 4000}, () => Math.floor(Math.random() * 4000))

// randomly generated N = 3 length array 0 <= A[N] <= 2
// const array = Array.from({length: 3}, () => Math.floor(Math.random() * 3))``````

## Test runner

Testing in
TestOps/sec
``````const min = Math.min(...array)
const max = Math.max(...array)
console.log(`Minimum: \${min}, Maximum: \${max}`)``````
Using Function.prototype.apply()
``````const min = Math.min.apply(null, array)
const max = Math.max.apply(null, array)
console.log(`Minimum: \${min}, Maximum: \${max}`)``````
Using .sort()
``````array.sort((a,b) => a-b) // Sort numerically, ascending
const min = array[0]
const max = array[array.length-1]
console.log(`Minimum: \${min}, Maximum: \${max}`)``````
Using a for loop
``````const forLoopMinMax = () => {
let min = array[0], max = array[0]

for (let i = 1; i < array.length; i++) {
let value = array[i]
min = (value < min) ? value : min
max = (value > max) ? value : max
}

return [min, max]
}
const [forLoopMin, forLoopMax] = forLoopMinMax()
console.log(`Minimum: \${forLoopMin}, Maximum: \${forLoopMax}`)``````
``````const minUsingReduce = () => array.reduce((min, currentValue) => Math.min(min, currentValue), array[0])