There are no built-in functions for finding the max or min value in an array.

However, after you have sorted an array, you can use the index to obtain the highest and lowest values.

Sorting ascending:

Example

const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
// now points[0] contains the lowest value
// and points[points.length-1] contains the highest value

Sorting descending:

Example

const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
// now points[0] contains the highest value
// and points[points.length-1] contains the lowest value
Sorting a whole array is a very inefficient method if you only want to find the highest (or lowest) value.
 

Using Math.max() on an Array

You can use Math.max.apply to find the highest number in an array:

Example

function myArrayMax(arr) {
  return Math.max.apply(null, arr);
}
 

Math.max.apply(null, [1, 2, 3]) is equivalent to Math.max(1, 2, 3).


Using Math.min() on an Array

You can use Math.min.apply to find the lowest number in an array:

Example

function myArrayMin(arr) {
  return Math.min.apply(null, arr);
}
 

Math.min.apply(null, [1, 2, 3]) is equivalent to Math.min(1, 2, 3).


My Min / Max JavaScript Methods

The fastest solution is to use a "home made" method.

This function loops through an array comparing each value with the highest value found:

Example (Find Max)

function myArrayMax(arr) {
  let len = arr.length;
  let max = -Infinity;
  while (len--) {
    if (arr[len] > max) {
      max = arr[len];
    }
  }
  return max;
}
 

This function loops through an array comparing each value with the lowest value found:

Example (Find Min)

function myArrayMin(arr) {
  let len = arr.length;
  let min = Infinity;
  while (len--) {
    if (arr[len] < min) {
      min = arr[len];
    }
  }
  return min;
}
 



Practice Excercise Practice now