In this article, I will explain 2 methods for finding the min and max values from an Array in JavaScript.
How to find the min value of an array in JavaScript?
Method 1 - Using Math.min()
This is the easiest method. We will be using Math.min().
The way Math.min() works is that it expects values seperated by commas (i.e Math.min(1,2,3,4)).
But since we will be passing an array, we need to destructure it by using the spread syntax. Check out the example:
let arr = [5,1,2,3];
let min = Math.min(...arr);
// min = 1;
❗️ Don't forget to use the spread syntax (the three dots that expands the array into individual elements)! If you don't do the …arr then you will get NaN (not a number).
Method 2 - Using loops
This is a longer way to get the min value.
We will store the first value of the array as the temporary min. Then we will loop from the second value (index 1) and start comparing all the remaining values with the current "min", if the value is less than the current min then the min will become that value.
let arr = [5,1,2,3];
let min = arr[0];
for(let i=1; i<arr.length; i++){
if(arr[i] < min){
min = arr[i]
}
}
// min = 1;
How to find the max value of an array in JavaScript?
Method 1 - using Math.max()
This is the easiest method. We will be using Math.max().
The way Math.max() works is that it expects values seperated by commas (i.e Math.max(1,2,3,4)).
But since we will be passing an array, we need to destructure it by using the spread syntax. Check out the example:
let arr = [5,1,2,3];
let max = Math.max(...arr);
// max = 5;
❗️ Don't forget to use the spread syntax (the three dots that expands the array into individual elements)! If you don't do the …arr then you will get NaN (not a number).
Method 2 - Using loops
This is a longer way to get the max value.
We will store the first value of the array as the temporary max. Then we will loop from the second value (index 1) and start comparing all the remaining values with the current "max", if the value is greater than the current max then the max will become that value.
let arr = [5,1,2,3];
let max = arr[0];
for(let i=1; i<arr.length; i++){
if(arr[i] > max){
max = arr[i]
}
}
// max = 5;
You now know how to find the max and min values of an array using JS.
In my opinion, the Math.min() and Math.max() methods are the cleaner ways to do it.