Member-only story
Finding the Min/Max Value in an Array in JavaScript
Method 1: Using Math.max and Math.min
The Math object’s Math.min() and Math.max() methods are static methods that return the minimum and maximum elements of a given array. The spread(…) operator could pass these functions into an array. The spread operator allows an iterable to expand in places where multiple arguments are expected. In this case, it automatically expands the array and gives the numbers to the functions.
const arr = [50, 10, 20, 40];
const maxValue = Math.max(...arr);
const minValue = Math.min(...arr);
console.log(minValue); //10
console.log(maxValue); //50
Method 2: Iterating through the Array
Iterating through the array and keeping track of the minimum and maximum elements. The minimum and maximum element can be kept track by iterating through all the elements in the array and updating the minimum and maximum element up to that point by comparing them to the current minimum and maximum values. The minimum and maximum values are initialized to Infinity and -Infinity.
function findMinMax() {
let Arr = [50, 60, 20, 10, 40];
let minValue = Infinity;
let maxValue = -Infinity;
for (let item of Arr) {
// Find minimum value
if (item < minValue)
minValue = item;
// Find maximum value
if (item > maxValue)
maxValue = item;
}
console.log("Minimum element is:" + minValue);
console.log("Minimum element is:" + maxValue);
}
findMinMax();