In javascript it is possible to find the minimum and maximum value of an integer in an array
This is among the most common coding interview question that interviewers use to test the skills of developers.
Chapter 1 Using in built library
The simplest method of finding the minimum value of an array is by using the in built Math
library that has both Math.min
and Math.max
functions for finding minimums and maximums.
//Find the maximum in an array
let maxValue = Math.max(...arr);
//Find the minimum in an array
let minValue = Math.min(...arr);
Chapter 2 Using in for
loops
One can also accomplish this by the use of a for
loop as shown
//Find the maximum in an array
function arrMax(arr) {
let maxArr = Number.NEGATIVE_INFINITY;
for (let i = 0; i < arr.length; i++) {
if (arr[i] >= maxArr) {
maxArr = arr[i];
}
}
}
The same can be used in finding the smallest number
//Find the minimum in an array
function arrMin(arr) {
let minArr = Number.POSITIVE_INFINITY;
for (let i = 0; i < arr.length; i++) {
if (arr[i] <= minArr) {
minArr = arr[i];
}
}
}
Number.NEGATIVE_INFINITY
and Number.POSITIVE_INFINITY
are used in javascript to represent the lowest and highest number representation of the language.
Chapter 3 Using in reduce
function
Alternatively, one may opt to use the Array.prototype.reduce()
function in finding the minimum and maximum values of an array. The reduce function simply uses a provided callback to return a single element. In our case, this is either the minimium value or the maximum value.
//Find the minimum in an array
function arrMin(arr) {
return arr.reduce((a, b) => (a < b ? b : a));
}
//Find the maximum in an array
function arrMax(arr) {
return arr.reduce((a, b) => (a < b ? a : b));
}
The (a, b) => (a < b ? b : v)
expression works as an if.. else
statement. In javascript it is referred to as the Ternary operator with a method signature as
variable = Expression1 ? Expression2: Expression3
Leave a like ❤️ if you found this useful
Happy coding 🔥 🔥
Top comments (0)