JavaScript: Get Min and Max Element of Array

Introduction

When working with JavaScript, we oftentimes encounter situations that require us to obtain the minimum and maximum elements of an array - be it for setting boundaries for a slider or displaying the statistics to a user.

In this article, we'll take a look at how to get the minimum and the maximum element of an array in JavaScript. We'll also look at four different methods and compare their speeds when dealing with large arrays.

How to Get Min and Max Elements of an Array Using the Math Object

Math is JavaScript's built-in global convenience object containing a lot of methods and constants you might need when performing mathematical operations. Two methods that we'll use in this article are Math.min() and Math.max() - both of them accept a list of numbers as arguments. As their names suggest, one returns the element with the lowest value, and the other returns one whose value is the highest:

console.log(Math.min(20, 23, 27)); // 20
console.log(Math.max(20, 23, 27)); // 27

console.log(Math.min(-20, -23, -27)); // -27
console.log(Math.max(-20, -23, -27)); // -20

If at least one of the passed elements is not a number or cannot be converted to a number, both Math.min() and Math.max() returns NaN:

console.log(Math.min('-20', -23, -27)); // -27
console.log(Math.max('number', -23, -27)); // NaN

Similarly, if we try to pass an array as an argument of the Math.min() function, we get a NaN, since it's treated as a single element, which can't be converted to a scalar value:

const myArray = [2, 3, 1];
console.log(Math.min(myArray)); // NaN

However, a quick fix for this is to use the spread operator to unwrap the elements:

const myArray = [2, 3, 1];
console.log(Math.min(...myArray)); // 1

If you'd like to read more about the Spread Operator - read our Guide to the Spread Operator in JavaScript!

Get Max and Min Element with reduce()

Reduction operations, sometimes known as folding, are some of the most powerful operations from functional programming, with a wide variety of applications. The reduce() function, runs a reducer function (defined in a callback) on each array element and returns a single value in the end.

It's worth covering the method due to how universally it can be applied:

const myArray = [20, 23, 27];

let minElement = myArray.reduce((a, b) => {
    return Math.min(a, b);
});

console.log(minElement); // 20

Find Min and Max Element with apply()

The apply() method is used to invoke a function with a given this value and an array of arguments. This makes it possible for us to enter arrays into the Math.min() static function:

const myArray = [20, 23, 27];

let minElement = Math.min.apply(Math, myArray);
console.log(minElement); // 20
// Or
let minElement = Math.min.apply(null, myArray);
console.log(minElement); // 20

Getting Min and Max Elements With Standard Loops - Fastest Performance

Loops are used in JavaScript to perform repeated tasks based on a condition. Conditions return true or false. A loop will continue running until the defined condition returns false. In our case, we will be making use of the for loop - it is commonly used to run code a number of times.

Get Minimum Element

First, we'll initialize the minimum element to the first element of an array. Then, we loop through the entire array to see if the value of any other element is less than the current minimum value - if it is, we'll set the new minimum value to the value of the current element:

const myArray = [20, 23, 27];

let minElement = myArray[0];
for (let i = 1; i < arrayLength; ++i) {
    if (myArray[i] < minElement) {
        minElement = myArray[i];
    }
}

console.log(minElement); // 20

Get Maximum Element

We'll first initialize the maximum element to the first element in the array. Then we will loop through the entire array to see if any other element is greater than the initialized element, so it replaces it:

const myArray = [20, 23, 27];

let maxElement = myArray[0];
for (let i = 1; i < arrayLength; ++i) {
    if (myArray[i] > maxElement) {
        maxElement = myArray[i];
    }
}

console.log(maxElement); // 27

Performance Benchmark

Using JS Benchmark - we've run all of these approaches on varying input, from 100 to 1000000 elements in the array. The performance is relative, and depends on the length of the array.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

  • For small arrays (100), the reduce() method performed the best, followed by standard loops, the spread operator and then the apply() method. The runner ups are almost equal in performance.
  • For medium arrays (1000), the standard loops perform the best, followed by reduce(), the spread operator and the apply() method. Standard loops significantly faster than reduce() here, which in turn, is fairly faster than the runner ups.
  • For really large arrays (1000000), the standard loops outperform all other methods to such a large degree that the case for standard loops is very strong.

Standard loops scale really well, and only lose out to the competition when applied to small arrays. If you're dealing with a few items, or smaller arrays, all of the methods will be fairly seamless. The larger the array, the bigger the benefit of using standard loops.

Note: Don't take benchmarks at face value! They're run on different machines, with likely different browser versions and JS engines. Test these out in your application and choose the scalable, fastest option for your own use case.

Conclusion

In this guide, we've taken a look at how to get the minimum and maximum elements of an array in JavaScript. We've taken a look at the Math.min() and Math.max() methods, the spread operator, the reduce() method, the apply() method and wrote a custom approach to getting the elements through a for loop.

Finally, we've benchmarked the results, noting that it doesn't really matter which approach you use for small arrays, while you should tend to use standard for loops for larger arrays.

Last Updated: April 6th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Joel OlawanleAuthor

Frontend Developer & Technical Writer

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms