Finding the Minimum and Maximum Values of an Array in JavaScript

cavein254

John Muthua

Posted on September 23, 2022

Finding the Minimum and Maximum Values of an Array in JavaScript

singularity
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);
Enter fullscreen mode Exit fullscreen mode

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];
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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];
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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));
}
Enter fullscreen mode Exit fullscreen mode
//Find the maximum in an array
function arrMax(arr) {
  return arr.reduce((a, b) => (a < b ? a : b));
}
Enter fullscreen mode Exit fullscreen mode

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 🔥 🔥

💖 💪 🙅 🚩
cavein254
John Muthua

Posted on September 23, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related