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.
Syntax:
minValue = Infinity;
maxValue = -Infinity;
for (item of array) {
// Find minimum value
if (item < minValue)
minValue = item;
// Find maximum value
if (item > maxValue)
maxValue = item;
}
Example: We will be iterating through the elements of the array to find the max and min elements from the array.
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();
Output
Minimum element is:10 Minimum element is:60
Find the min/max element of an Array using JavaScript
Finding the minimum or maximum element of an array in JavaScript involves determining the smallest or largest value from the array’s elements. This operation is crucial for various tasks, such as data analysis, optimization problems, and comparisons within algorithms.
The minimum and maximum elements in an array can be found using the following methods:
Table of Content
- Using Math.min() and Math.max() Methods
- Iterating through the Array
- Using JavaScript Array.reduce() method
- Using apply method
- Using spread operator
Contact Us