Computer >> Computer tutorials >  >> Programming >> Javascript

How to find the minimum value of an array in JavaScript?


We can find the minimum value of an array using Math.min() and sort()

1) Math.min() 

Math.min() function usually takes all the elements in an array and scrutinize each and every value to get the minimum value.It's methodology is discussed in the below example.

Example

<html>
<body>
<script>
   function minimum(value) {
      if (toString.call(value) !== "[object Array]")
      return false;
      return Math.min.apply(null, value);
   }
   document.write(minimum([6,39,55,1,44]));
</script>
</body>
</html>

Output

1

2)  sort()

Using sort() and compare functions we can write the elements in ascending or descending order, later on using length property we can find the minimum in the following way 

Example

<html>
<body>
<input type ="button" onclick="myFunction()" value = "clickme">
<p id="min"></p>
<script>
   var numbers = [6,39,55,1,44];
   document.getElementById("min").innerHTML = numbers;
   function myFunction() {
      numbers.sort(function(a, b){return b - a});
   document.getElementById("min").innerHTML = numbers;
   document.write(numbers[numbers.length-1]);
}
</script>
</body>
</html>

After running the program the out put will be shown as in  the following image

How to find the minimum value of an array in JavaScript?

Output

On clicking the click me button above the output would display as

1