Find the min/max element of an array in JavaScript

Viewed 1337499

How can I easily obtain the min or max element of a JavaScript array?

Example pseudocode:

let array = [100, 0, 50]

array.min() //=> 0
array.max() //=> 100
57 Answers

Alternative Methods


The Math.min and Math.max are great methods to get the minimum and maximum item out of a collection of items, however it's important to be aware of some cavities that can comes with it.

Using them with an array that contains large number of items (more than ~10⁷ items, depends on the user's browser) most likely will crash and give the following error message:

const arr = Array.from(Array(1000000).keys());
Math.min(arr);
Math.max(arr);

Uncaught RangeError: Maximum call stack size exceeded

UPDATE
Latest browsers might return NaN instead. That might be a better way to handle errors, however it doesn't solve the problem just yet.

Instead, consider using something like so:

function maxValue(arr) {
  return arr.reduce((max, val) => max > val ? max : val)
}

Or with better run-time:

function maxValue(arr) {
  let max = arr[0];

  for (let val of arr) {
    if (val > max) {
      max = val;
    }
  }
  return max;
}

Or to get both Min and Max:

function getMinMax(arr) {
  return arr.reduce(({min, max}, v) => ({
    min: min < v ? min : v,
    max: max > v ? max : v,
  }), { min: arr[0], max: arr[0] });
}

Or with even better run-time*:

function getMinMax(arr) {
  let min = arr[0];
  let max = arr[0];
  let i = arr.length;
    
  while (i--) {
    min = arr[i] < min ? arr[i] : min;
    max = arr[i] > max ? arr[i] : max;
  }
  return { min, max };
}

* Tested with 1,000,000 items:
Just for a reference, the 1st function run-time (on my machine) was 15.84ms vs 2nd function with only 4.32ms.

Two ways are shorter and easy:

let arr = [2, 6, 1, 0]

Way 1:

let max = Math.max.apply(null, arr)

Way 2:

let max = arr.reduce(function(a, b) {
    return Math.max(a, b);
});

A simple solution to find the minimum value over an Array of elements is to use the Array prototype function reduce:

A = [4,3,-9,-2,2,1];
A.reduce((min, val) => val < min ? val : min, A[0]); // returns -9

or using JavaScript's built-in Math.Min() function (thanks @Tenflex):

A.reduce((min,val) => Math.min(min,val), A[0]);

This sets min to A[0], and then checks for A[1]...A[n] whether it is strictly less than the current min. If A[i] < min then min is updated to A[i]. When all array elements has been processed, min is returned as the result.

EDIT: Include position of minimum value:

A = [4,3,-9,-2,2,1];
A.reduce((min, val) => val < min._min ? {_min: val, _idx: min._curr, _curr: min._curr + 1} : {_min: min._min, _idx: min._idx, _curr: min._curr + 1}, {_min: A[0], _idx: 0, _curr: 0}); // returns { _min: -9, _idx: 2, _curr: 6 }

For a concise, modern solution, one can perform a reduce operation over the array, keeping track of the current minimum and maximum values, so the array is only iterated over once (which is optimal). Destructuring assignment is used here for succinctness.

let array = [100, 0, 50];
let [min, max] = array.reduce(([prevMin,prevMax], curr)=>
   [Math.min(prevMin, curr), Math.max(prevMax, curr)], [Infinity, -Infinity]);
console.log("Min:", min);
console.log("Max:", max);

To only find either the minimum or maximum, we can use perform a reduce operation in much the same way, but we only need to keep track of the previous optimal value. This method is better than using apply as it will not cause errors when the array is too large for the stack.

const arr = [-1, 9, 3, -6, 35];

//Only find minimum
const min = arr.reduce((a,b)=>Math.min(a,b), Infinity);
console.log("Min:", min);//-6

//Only find maximum
const max = arr.reduce((a,b)=>Math.max(a,b), -Infinity);
console.log("Max:", max);//35

let array = [267, 306, 108] let longest = Math.max(...array);

I thought I'd share my simple and easy to understand solution.

For the min:

var arr = [3, 4, 12, 1, 0, 5];
var min = arr[0];
for (var k = 1; k < arr.length; k++) {
  if (arr[k] < min) {
    min = arr[k];
  }
}
console.log("Min is: " + min);

And for the max:

var arr = [3, 4, 12, 1, 0, 5];
var max = arr[0];
for (var k = 1; k < arr.length; k++) {
  if (arr[k] > max) {
    max = arr[k];
  }
}
console.log("Max is: " + max);

Aside using the math function max and min, another function to use is the built in function of sort(): here we go

const nums = [12, 67, 58, 30].sort((x, y) => 
x -  y)
let min_val = nums[0]
let max_val = nums[nums.length -1]

For an array containing objects instead of numbers:

arr = [
  { name: 'a', value: 5 },
  { name: 'b', value: 3 },
  { name: 'c', value: 4 }
]

You can use reduce to get the element with the smallest value (min)

arr.reduce((a, b) => a.value < b.value ? a : b)
// { name: 'b', value: 3 }

or the largest value (max)

arr.reduce((a, b) => a.value > b.value ? a : b)
// { name: 'a', value: 5 }

let arr=[20,8,29,76,7,21,9]
Math.max.apply( Math, arr ); // 76

array.sort((a, b) => b - a)[0];

Gives you the maximum value in an array of numbers.

array.sort((a, b) => a - b)[0];

Gives you the minimum value in an array of numbers.

let array = [0,20,45,85,41,5,7,85,90,111];

let maximum = array.sort((a, b) => b - a)[0];
let minimum = array.sort((a, b) => a - b)[0];

console.log(minimum, maximum)

let arr = [2,5,3,5,6,7,1];

let max = Math.max(...arr); // 7
let min = Math.min(...arr); // 1

Try

let max= a=> a.reduce((m,x)=> m>x ? m:x);
let min= a=> a.reduce((m,x)=> m<x ? m:x);

let max= a=> a.reduce((m,x)=> m>x ? m:x);
let min= a=> a.reduce((m,x)=> m<x ? m:x);

// TEST - pixel buffer
let arr = Array(200*800*4).fill(0); 
arr.forEach((x,i)=> arr[i]=100-i%101); 

console.log('Max', max(arr));
console.log('Min', min(arr))

For Math.min/max (+apply) we get error:

Maximum call stack size exceeded (Chrome 74.0.3729.131)

// TEST - pixel buffer
let arr = Array(200*800*4).fill(0); 
arr.forEach((x,i)=> arr[i]=100-i%101); 

// Exception: Maximum call stack size exceeded

try {
  let max1= Math.max(...arr);          
} catch(e) { console.error('Math.max :', e.message) }

try {
  let max2= Math.max.apply(null, arr); 
} catch(e) { console.error('Math.max.apply :', e.message) }


// same for min

Here's a plain vanilla JS approach.

function getMinArrayVal(seq){
    var minVal = seq[0];
    for(var i = 0; i<seq.length-1; i++){
        if(minVal < seq[i+1]){
        continue;
        } else {
        minVal = seq[i+1];
        }
    }
    return minVal;
}

Below script worked for me in ndoejs:

 var numbers = [1, 2, 3, 4];
 console.log('Value:: ' + Math.max.apply(null, numbers) ); // 4

well I would like to do this in the below way

const findMaxAndMin = (arr) => {
  if (arr.length <= 0) return -1;
  let min = arr[0];
  let max = arr[0];
  arr.forEach((n) => {
    n > max ? (max = n) : false;
    n < min ? (min = n) : false;
  });
  return [min, max];
};

A recursive solution to the problem

const findMinMax = (arr, max, min, i) => arr.length === i ? {
    min,
    max
  } :
  findMinMax(
    arr,
    arr[i] > max ? arr[i] : max,
    arr[i] < min ? arr[i] : min,
    ++i)

const arr = [5, 34, 2, 1, 6, 7, 9, 3];
const max = findMinMax(arr, arr[0], arr[1], 0)
console.log(max);

Another solution

   let arr = [1,10,25,15,31,5,7,101];
    let sortedArr = arr.sort((a, b) => a - b)

    let min = sortedArr[0];
    let max = sortedArr[arr.length-1]

    console.log(`min => ${min}. Max => ${max}`)

screenshot

Alternative Solns

class SmallestIntegerFinder {
  findSmallestInt(args) {
    return args.reduce((min,item)=>{ return (min<item ? min : item)});
  }
}

class SmallestIntegerFinder {
  findSmallestInt(args) {
    return Math.min(...args)
  }
}

class SmallestIntegerFinder {
  findSmallestInt(args) {
    return Math.min.apply(null, args);
  }
}

class SmallestIntegerFinder {
  findSmallestInt(args) {
    args.sort(function(a, b) {
    return a - b; } )
    return args[0];
  }
}

For learning purpose, you can do it by using variables and for loop without using built-in functions.

// Input sample data to the function
var arr = [-1, 0, 3, 100, 99, 2, 99];
// Just to show the result
console.log(findMinMax(arr));

function findMinMax(arr) {
  let arraySize = arr.length;
  if (arraySize > 0) {
    var MaxNumber = MinNumber = arr[0];
    for (var i = 0; i <= arraySize; i++) {
      if (arr[i] > MaxNumber) {
        MaxNumber = arr[i];
      }else if(arr[i] < MinNumber) {
        MinNumber = arr[i];
      }
    }
    var minMax = [MinNumber,MaxNumber];
    return minMax;
  } else {
    return 0;
  }
}

To add to the many good answers here, here is a typescript version that can handle lists where some values are undefined.

How it can be used:

const testDates = [
  undefined,
  new Date('July 30, 1986'),
  new Date('July 31, 1986'),
  new Date('August 1, 1986'),
]
const max: Date|undefined = arrayMax(testDates); // Fri Aug 01 1986
const min: Date|undefined = arrayMin(testDates); // Min: Wed Jul 30 1986
const test: Date = arrayMin(testDates); // Static type error
const anotherTest: undefined = arrayMin(testDates); // Static type error

The definitions (the notEmpty definition is from this post):

function arrayMax<T>(values?: (T | null | undefined)[]): T | undefined {
    const nonEmptyValues = filterEmpty(values);
    if (nonEmptyValues.length === 0) {
        return undefined;
    }
    return nonEmptyValues.reduce((a, b) => (a >= b ? a : b), nonEmptyValues[0]);
}

function arrayMin<T>(values?: (T | null | undefined)[]): T | undefined {
    const nonEmptyValues = filterEmpty(values);
    if (nonEmptyValues.length === 0) {
        return undefined;
    }
    return nonEmptyValues.reduce((a, b) => (a <= b ? a : b), nonEmptyValues[0]);
}

function filterEmpty<T>(values?: (T | null | undefined)[] | null): T[] {
    return values?.filter(notEmpty) ?? [];
}

function notEmpty<T>(value: T | null | undefined): value is T {
    if (value === null || value === undefined) return false;
    const testDummy: T = value;
    return true;
}

I didn't use the Math.max function as suggested in the documentation because this way I can use this function with any comparable objects (if you know how to type this let me know so I can better define T).

Here is one more example. Calculate the Max/Min value from an array with lodash.

let array = [100, 0, 50];
var func = _.over(Math.max, Math.min);
var [max, min] = func(...array);
// => [100, 0]
console.log(max);
console.log(min);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Related