In JavaScript, to get the min value in an array we can do this by using a for loop with an if conditional statement. Here is a function to get the min number of an array.

function getMinNum(){
  var minNumber = arrayOfNumber[0];
  for (var i = 0; i < arrayOfNumber.length; i++) {
    if( arrayOfNumber[i] < minNumber ){
      minNumber = arrayOfNumber[i];
    }
  }
  return minNumber;
}

Let's see an example of this function below.


In the example below, we will have an array of numbers. We will use our getMinNum() function we created above to find the minimum number and return it.

var numbersArray = [4,3,5,8,14,67,56,23];

function getMinNum(){
  var minNumber = numbersArray[0];
  for (var i = 0; i < numbersArray.length; i++) {
    if( numbersArray[i] < minNumber ){
      minNumber = numbersArray[i];
    }
  }
  return minNumber;
}

var minNum = getMinNum(numbersArray);

The variable minNum above would have value 3.

Interactive Example of Getting the Min Value of an Array

Below we will provide code to let the user input as many numbers as they want separated by a comma(,).

Here is the simple HTML set up:

Type as many numbers as you want separated by a comma.

If the numbers are not separated by a comma only, this example will not work.

Get Min Number

We will then create an array of numbers from this input and find the min value using the getMinNum() function we created above.

To create an array from the string of numbers the user provides, we will use the split() method along with the Array map() method. We will add this code to our getMinNum function.

We will update the results below using the textContent property.

function getMinNum(){
  
  //Get the user input
  var userInput = document.getElementById("userArr").value;

  //Convert user input to an array of numbers
  var numbersArray = userInput.split(',').map(Number);

  //Find the min number
  var minNumber = numbersArray[0];
  for (var i = 0; i < numbersArray.length; i++) {
    if( numbersArray[i] < minNumber ){
      minNumber = numbersArray[i];
    }
  }

  //Display the min number
  document.getElementById("results").textContent = "The min number is: " + minNumber;

}

The final code and output for this example is below:

Code Output:

Type as many numbers as you want separated by a comma.

If the numbers are not separated by a comma only, this example will not work.

Get Min Number

Full Code:

Type as many numbers as you want separated by a comma.

If the numbers are not separated by a comma only, this example will not work.

Get Min Number

Hopefully this article has helped you to understand how to get the min value in an array using JavaScript.

Categorized in:

JavaScript,

Last Update: March 15, 2024