How to find min/max values without Math functions in JavaScript ?
In this article, we will learn how to find the minimum and maximum values in an array without using Math functions. We know that Math.max() returns the maximum number passed in an array whereas Math.min() returns the minimum number passed.
Approach: The same functionality of the Math functions can be implemented using a loop that will iterate the numbers present in the array to find maximum and minimum values inside the array.
We will keep checking all the elements in the array using a loop. If we find any element greater than the previous “max” value, we set that value as the max value. Similarly, we keep on checking for any element lesser than the “min” value. If we get any such element, we replace the value of “min” with a smaller value. Thus, using the loop function, we can get the maximum and minimum values entered in an array/list.
Example 1: The below example will demonstrate the above approach.
JavaScript
const array = [-1, 2, -5, 8, 16];
let max = array[0], min = array[0];
for (let i = 0; i < array.length; i++) {
if (array[i] > max) { max = array[i]; }
if (array[i] < min) { min = array[i]; }
}
console.log( "max = " + max);
console.log( "min = " + min);
|
Output: The maximum and the minimum number of the array is found using the approach.
max = 16
min = -5
Example 2: In this example, we will get max and min without function.
Javascript
const arr = [-7,-10,8,6,5,4];
let max = arr[0]
let min = arr[0];
for (let i = 0; i < arr.length; i++) {
if (arr[i] > max) { max = arr[i]; }
if (arr[i] < min) { min = arr[i]; }
}
console.log( "Max element is: " + max);
console.log( "Min element is:" +min);
|
Output:
Max element is: 8
Min element is:-10
Last Updated :
28 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...