Find Min and Max Number in an Array

Last modified: 
Tuesday, April 21st, 2015

This is a Javascript algorithm to find the minimum and maximum numeric values in an array. It will ignore any members that are not numbers.

/**
* Takes an array of numbers as input and returns the highest and lowest
* value found or false if no numbers are found. Ignores any non-numeric
* members of the input array.
*
* @param values
*   An array of numbers.
* @return 
*   An array [min, max] or false if no numbers are found.
*/
function calculateRange(values) {
  
  var nums = [];
  var min = null;
  var max = null;
 
  for (var i = 0; i < values.length; i++) {  
    if (typeof values[i] == "number") {
      nums.push(values[i]);
    }
  }
 
  if (nums.length > 0) {
    min = nums[0];
    max = nums[0];
    for (var i = 0; i < nums.length; i++) {
      if (nums[i] < min) {
        min = nums[i];
      }
      if (nums[i] > max) {
        max = nums[i];
      }
    }
    return [min, max];
  }
  else {
    return false;
  } 
}

Example 1

Get the minimum and maximum values from a mixed array.

var values = [300, 2, 3, 8, 10, 3902, "banana", -1.2, "pear"];
range = calculateRange(values);
console.log(range); // Returns [ -1.2, 3902 ]

Example 2

Return false when no numbers are found.

var values = [ "banana", "pear"];
range = calculateRange(values);
console.log(range); // Returns false


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.