In this post, we will see how to get the min/max elements from an array in JavaScript. The minimum and maximum elements in an array can be found using below methods:
Methods to find min/max from array
- Using a loop
- Using reduce method
- Using built in methods Math.min and Math.max
Method 1 — Using a loop
In this approach, you use a loop to iterate through each element of the unsorted array and keep track of the minimum and maximum values found.
Let’s try this out -
In the above example, first, we initialize minVal and maxVal to keep track of min and max values and set them to the first element of the array. Now start iterating through the array from the second element.
For each element in the array, we checked if the number is smaller than minVal, if yes assign it to minVal. If the number is larger than maxVal, we assign it to maxVal.
After iterating all the elements of the array, we will have min and max values in minVal and maxVal.
Read out more at : https://codeymaze.com/find-the-min-max-element-of-an-array-using-javascript/