Function that returns the minimum and maximum value of an array in JavaScript


Understanding the range of values within an array is a crucial aspect of data analysis and manipulation in JavaScript. When faced with large datasets or complex algorithms, having a reliable function that can efficiently determine the minimum and maximum values of an array becomes indispensable. This article delves into the intricacies of creating a robust JavaScript function that can effortlessly extract the extreme values from an array, enabling developers to gain valuable insights and make informed decisions based on the data at hand. By exploring the step-by-step implementation and leveraging rarely used programming techniques, we empower developers to enhance their code's efficiency and unlock new possibilities for data-driven solutions.

Problem Statement

Design a JavaScript function that takes an array of numbers as input and returns the minimum and maximum values present in the array. Implement the function to ensure efficient and accurate computation of the minimum and maximum values.

Sample Input −

const inputArray = [5, 2, 9, 1, 7, 4];

Sample Output −

const minValue = 1;
const maxValue = 9;

Note − The function should be able to handle arrays of any length and should return the minimum and maximum values as separate variables or in any suitable format.

Approach

In this article, we are going to see a number of different ways to solve the above problem statement in JavaScript −

  • Naive Approach

  • Sorting Approach

  • Divide and Conquer Approach

  • Linear Scan Approach

  • Binary Search Approach

  • Reduce Function Approach

Method 1: Naive Approach

In the naive approach, the minimum and maximum values of an array are found by initializing variables min and max to the first element. Then, the array is iterated starting from the second element. For each element, min and max are updated if the element is smaller or larger, respectively, than the current values. Ultimately, the array's minimal and maximal values are yielded as the "min" and "max" respectively.

Example

This code initializes variables min and max to the first element of the array and iterates through the array starting from the second element. For each element, it compares the element with the current min value and updates min if the element is smaller. It also compares the element with the current max value and updates max if the element is larger. Finally, it returns an object with the minimum and maximum values.

function findMinMax(array) {
   let min = array[0];
   let max = array[0];
   for (let i = 1; i < array.length; i++) {
      if (array[i] < min) {
         min = array[i];
      }
      if (array[i] > max) {
         max = array[i];
      }
   }
   return { min, max };
}

const array = [21, 88, 60, 91, 450, 29, 33];
const { min, max } = findMinMax(array);
console.log(`Minimum Element: ${min}`);
console.log(`Maximum Element: ${max}`);

Output

The following is the console output −

Minimum Element: 21
Maximum Element: 450

Method 2: Sorting Approach

In the sorting approach, start by arranging its elements from the smallest to the largest. The minimum value can then be found at the beginning of the sorted array, while the maximum value resides at the end. Therefore, to obtain both the minimum and maximum values, return the first and last elements of the sorted array, respectively.

Example

This code utilizes the sort() method to arrange the input array in ascending order. Once sorted, the first element (array[0]) represents the minimum value, while the last element (array[array.length - 1]) corresponds to the maximum value. The code ultimately returns an object containing both the minimum and maximum values.

function findMinMax(array) {
   array.sort((a, b) => a - b);
   return { min: array[0], max: array[array.length - 1] };
}

const array = [21, 88, 60, 91, 450, 29, 33];
const { min, max } = findMinMax(array);
console.log(`Minimum Element: ${min}`);
console.log(`Maximum Element: ${max}`);

Output

The following is the console output −

Minimum Element: 21
Maximum Element: 450

Method 3: Divide and Conquer Approach

The Divide and Conquer approach for finding the minimum and maximum values in an array involves dividing the array into two halves. Through recursive calls, the minimum and maximum values are found separately in each half. These values are then compared, selecting the smaller one as the overall minimum and the larger one as the overall maximum. Finally, the minimum and maximum values are returned, providing the desired outcome.

Example

The recursive function findMinMax determines the minimum and maximum values in an array. If the array contains only one element, it returns an object with that element as both the minimum and maximum. Otherwise, it divides the array into two halves and recursively calls findMinMax on each half to find the minimum and maximum values. It then compares the minimum values of the two halves and selects the smaller one as the overall minimum, and does the same for the maximum values, selecting the larger one as the overall maximum. In the end, it yields an entity encompassing the minimal and maximal magnitudes.

function findMinMax(array) {
   if (array.length === 1) {
      return { min: array[0], max: array[0] };
   }
   const mid = Math.floor(array.length / 2);
   const left = findMinMax(array.slice(0, mid));
   const right = findMinMax(array.slice(mid));
   return {
      min: Math.min(left.min, right.min),
      max: Math.max(left.max, right.max),
   };
}

const array = [21, 88, 60, 91, 450, 29, 33];
const { min, max } = findMinMax(array);
console.log(`Minimum Element: ${min}`);
console.log(`Maximum Element: ${max}`);

Output

The following is the console output −

Minimum Element: 21
Maximum Element: 450

Method 4: Linear Scan Approach

In the linear scan approach, we begin by setting the variables min and max to the first element of the array. Next, we traverse through the array and compare each element with the current min and max values. If an element is smaller than the current min, we update min accordingly. On the other hand, if an element is larger than the current max, we update max. Finally, we return min and max as the minimum and maximum values of the array.

Example

The code iterates through the array, starting from the second element, and initializes variables min and max to the first element. It compares each element with the current min and max values, updating them if necessary. After iterating through all elements, it returns an object with the minimum and maximum values.

function findMinMax(array) {
   let min = array[0];
   let max = array[0];

   for (let i = 1; i < array.length; i++) {
      if (array[i] < min) {
         min = array[i];
      } else if (array[i] > max) {
         max = array[i];
      }
   }

   return { min, max };
}

const array = [21, 88, 60, 91, 450, 29, 33];
const { min, max } = findMinMax(array);
console.log(`Minimum Element: ${min}`);
console.log(`Maximum Element: ${max}`);

Output

The following is the console output −

Minimum Element: 21
Maximum Element: 450

Method 5: Binary Search Approach

The Binary Search Approach involves dividing the array into two halves and recursively finding the minimum and maximum values in each half. Then, the minimum values of the two halves are compared to select the smaller one as the overall minimum, and the maximum values are compared to select the larger one as the overall maximum. Finally, the minimum and maximum values are returned.

Example

The findMinMax function accepts an array, start index, and end index. If the start and end indices are the same, it returns an object with the single element as both the minimum and maximum. Otherwise, it calculates the middle index (mid) and recursively calls findMinMax on the left and right halves. It retrieves the minimum and maximum values from the left and right halves. Ultimately, it returns an object with the minimum value as the smaller of the two halves and the maximum value as the larger of the two halves.

function findMinMax(array, start = 0, end = array.length - 1) {
   if (start === end) {
      return { min: array[start], max: array[end] };
   }
   const mid = Math.floor((start + end) / 2);
   const left = findMinMax(array, start, mid);
   const right = findMinMax(array, mid + 1, end);
   return {
      min: Math.min(left.min, right.min),
      max: Math.max(left.max, right.max),
   };
}

const array = [21, 88, 60, 91, 450, 29, 33];
const { min, max } = findMinMax(array);
console.log(`Minimum Element: ${min}`);
console.log(`Maximum Element: ${max}`);

Output

The following is the console output −

Minimum Element: 21
Maximum Element: 450

Method 6: Reduce Function Approach

To find the minimum and maximum values in an array using the reduce() function, initialize the accumulator object with min and max properties set to the first element of the array. Then, iterate through each element of the array and update the min and max properties accordingly if a smaller or larger element is found. Lastly, return the accumulator entity encompassing the minimum and maximum values.

Example

In this code, the reduce() function is used to iterate through an array. The accumulator object is initialized with the min and max properties set to the first element of the array. As each element is processed, the reduce function compares it with the current min value and updates the min property if it is smaller. Likewise, it compares the element with the current max value and updates the max property if it is larger. Ultimately, the reduce function yields the accumulator entity encompassing the minimum and maximum values.

function findMinMax(array) {
   return array.reduce(
   (acc, current) => ({
      min: Math.min(acc.min, current),
      max: Math.max(acc.max, current),
   }),
   { min: array[0], max: array[0] }
   );
}

const array = [21, 88, 60, 91, 450, 29, 33];
const { min, max } = findMinMax(array);
console.log(`Minimum Element: ${min}`);
console.log(`Maximum Element: ${max}`);

Output

The following is the console output −

Minimum Element: 21
Maximum Element: 450

Conclusion

In denouement, the implementation of a function that provides both the minimum and maximum values of an array in JavaScript can greatly expedite data analysis and manipulation. By employing this algorithm, developers can leverage the breadth of their programming capabilities, facilitating efficient computation of extremities within a given dataset. Consequently, the utilization of such a function imbues applications with enhanced versatility and agility, affording users a more seamless and nuanced experience. In essence, the judicious incorporation of this lesser-known procedure can yield profound advantages, amplifying the potential of JavaScript in array manipulation and expanding the horizons of web development.

Updated on: 04-Aug-2023

346 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements