Find the maximum and minimum values of an array in JavaScript
There are a couple of ways to find the maximum and minimum values of an array in JavaScript.
Method 1 – Using min() and max()
The fastest way is by using the min() and max() methods. These two methods can be invoked using the Math object. The array is passed to the respective method with the spread operator. It is required to use the spread operator when passing an array to min() and max() methods, or they will return NaN.
Following is the syntax for the min() and max() methods.
Math.min(...array) // returns minumin value
Math.min(...array) // returns minimum value
Observe the following example.
const arr = [30, 20, 50, 80, 90, 40, 200, 10]; const minValue = Math.min(...arr); const maxValue = Math.max(...arr); console.log(minValue); //10 console.log(maxValue); //200
To omit the spread operator, use the apply() method with min() and max() methods.
Math.min.apply(null, array) // returns minumin value
Math.max.apply(null, array) // returns maximum value
Observe the following example.
const arr = [30, 20, 50, 80, 90, 40, 200, 10]; const minValue = Math.min.apply(null, arr); const maxValue = Math.max.apply(null, arr); console.log(minValue); //10 console.log(maxValue); //200
Method 2 – Using a for loop
The second method is using a for loop. Observe the following example.
const arr = [30, 20, 50, 80, 90, 40, 200, 10]; let minValue = arr[0]; let maxValue = arr[0]; for(var i = 1; i < arr.length; i++){ if(arr[i] < minValue){ minValue = arr[i]; } if(arr[i] > maxValue){ maxValue = arr[i]; } } console.log(minValue); // 10 console.log(maxValue); // 200
First, take two variables – minValue and maxValue to store minimum value and maximum value, respectively. The value at the 0th index is assigned to both of these variables. Then, a for loop is used, starting from the 1st index. In the for loop, two if statements are used.
The first if statement is checking if the iterating value is less than minValue or not. If yes, then the iterating value is assigned to the minValue.
if(arr[i] < minValue){ minValue = arr[i]; }
Similarly, the second if statement is checking if the iterating value is greater than maxValue or not. If yes, then the iterating value is assigned to the maxValue.
if(arr[i] > maxValue){ maxValue = arr[i]; }
Both of these methods work perfectly but the first one is faster and lighter. However, the first method will fail if there are too many values in an array.
Leave a Reply