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

JavascriptObject Oriented ProgrammingProgramming

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.

 Live Demo

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 

 Live Demo

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

Output

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

1
raja
Published on 22-May-2019 17:30:56
Advertisements