How to Find Min and Max Value in Array in Javascript
In this tutorial, you will learn how to find min and max value in array in javascript. When we talk about the min and max values in the array that means we are looking for the lowest and highest values in the array.
If you are a newbie, then you might find it a bit tricky, but this problem can be easily solved using a Math
object. It is one of the most useful built-in objects available in javascript because it contains certain useful properties and methods for mathematical constants and functions.
The Math
object contains min()
and max()
methods that can be used to accomplish our goal. The point to be noted here is that both the methods take zero or more numbers as an argument and then after the comparison, they return min and max values.
In the following example, we have an array of numbers. Upon click of a button, we will find the min and max values in the array and display them on the screen. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 3 elements in the HTML file (
div
,button
, andh1
). Thediv
element is just a wrapper for the rest of the elements. - The
button
element has“Get”
and theh1
element has“Result”
asinnerText
. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div> <button>Get</button> <h1>Result</h1> </div> <script src="script.js"></script> </body> </html>
body { text-align: center; } div { display: inline-block; } button { display: inline-block; padding: 10px 20px; }
Javascript
- We have selected the
button
element and theh1
element using thedocument.querySelector()
method and stored them inbtnGet
andresult
variables respectively. - We have global variable
numbers
which holds an array of numbers. - We have attached a
click
event listener to thebutton
element. - In the event handler function, we are calling
min()
andmax()
methods of theMath
object. We are using spread operator (…
) to spreadnumbers
array and passing that as an argument to these methods one by one. The returned values are stored in themin
andmax
variables. - We are forming a string using
min
andmax
variables and displaying that in theh1
element using theinnerText
property.
let btnGet = document.querySelector('button'); let result = document.querySelector('h1'); let numbers = [21,30,56,7,10,98, 100]; btnGet.addEventListener('click', () => { let min = Math.min(...numbers); let max = Math.max(...numbers); result.innerText = `min: ${min} - max: ${max}`; });