Get Maximum and Minimum value from a JavaScript Array

In this tute, we will discuss how to get Maximum and Minimum value from an Array in JavaScript. Before entering into the topic, let’s see a quick recap of arrays.

An array is a special variable that can contain more than one value. These elements can be of the same or different data types. Few examples of arrays are,

// Arrays of single type of elements
var arr1 = [5, 2, 3];
var arr2 = ['a', '3', 'hola'];
var arr3 = [55.3, 10.45];

// Array with multiple types of elements
var arr4 = [1, 'abc', 55.99];

JavaScript code to get Maximum and Minimum of an Array

There are a lot of possible ways to find the maximum and minimum values from an array based on the area used, query constraints, updates, and so on. Let’s see two simple and common methods to get max and min of an array in Javascript in this post.

Method 1:

In this method, we’ll make use of the max() and min() methods available in the built-in Math object.

Syntax:

Math.max(...array);    // Returns maximum element in array
Math.min(...array);    // Returns minimum element in array

Code Snippet:

var arr = [45, 10, 99, 55];

var max = Math.max(...arr);  // max = 99
var min = Math.min(...arr);  // min = 10

The Math.min() function returns the minimum elements of the array. Similarly, the Math.max() function returns the maximum element of the array.

 

Method 2:

In this method, let’s try to find the min and max elements without using the Math object. The idea is to iterate through all the elements and identify the minimum and maximum elements.

Algorithm:

  1. Firstly, start iterating through all the elements.
  2. At each index, if the element is greater than the current max, update the current max value with the current element.
  3. Similarly, if the element is smaller than the current min, update the current min value.
  4. Finally, return/print the min and max values.

Pseudocode:

max = lowest_value
min = largest_value
For element in array:
    If element > max then
        max = element
    If element < min then
        min = element

Code Snippet:

var arr = [45, 10, 99, 55];

var max = -1e19;         // Lower bound
var min = +1e19;         // Upper bound

for(var x in arr) {      // Traverse indices
    if(arr[x] > max)
        max = arr[x];    // Update max if arr[x] is greater
    if(arr[x] < min)
        min = arr[x];   // Update min if arr[x] is smaller
}

Time Complexity:

The time complexity is O(n). There are n elements in the array and every element is visited once.

 

Finally, If you have any queries or doubts on how to get maximum and minimum of an array in JavaScript, simply comment in the comment section provided below.

Also, read:

Leave a Reply

Your email address will not be published. Required fields are marked *