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

Benchmark created by djD-REK on


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

Ready to run.

Testing in
TestOps/sec
Using the spread operator
const min = Math.min(...array)
const max = Math.max(...array)
console.log(`Minimum: ${min}, Maximum: ${max}`)
ready
Using Function.prototype.apply()
const min = Math.min.apply(null, array)
const max = Math.max.apply(null, array)
console.log(`Minimum: ${min}, Maximum: ${max}`)
ready
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}`)
ready
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}`)
ready
Using .reduce()
const minUsingReduce = () => array.reduce((min, currentValue) => Math.min(min, currentValue), array[0])
const maxUsingReduce = () => array.reduce((max, currentValue) => Math.max(max, currentValue), array[0])
console.log(`Minimum: ${minUsingReduce()}, Maximum: ${maxUsingReduce()}`)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by djD-REK on