JavaScript – Three Ways to Get Maximum Value in an Array

What happened

Recently, while working on a problem – LeetCode #300 Longest Increasing Subsequence Solution & Explanation, I needed to get the maximum value of an array in JavaScript.

However, I found that compared to C#’s LINQ, Java’s Stream, and Python 3’s versatile max function, the impression of JavaScript might still be stuck with traditional for loop comparisons.

So today, let’s summarize three different methods to obtain the maximum value in an array using JavaScript.

Solution

solution 1 – for loop

const arr = [12,20,8,44,31];
const max = arr[0];
for(let i=1; i<arr.length; i++){
    if(arr[i]>max){
        max = arr[i];
    }
}

Certainly, it’s probably the most commonly used approach: setting the first element of the array as the provisional maximum value and iterating through the array in a for loop to compare each element.

In times when ES6 features are not supported, this method is the only option available. Remember to replace const and let with var (both are ES6 syntax).

solution 2 – Array.reduce

const arr = [12,20,8,44,31];
const max = arr.reduce((max, current) => {
    return current > max ? current : max;
}, arr[0]);

This code snippet utilizes ES6’s reduce syntax, which allows iterative computation.

Within this function, each element is compared with the current maximum value. If the current element is greater than the current maximum, it becomes the new maximum value. Finally, the maximum value is returned.

Regarding the initial value, if not provided, reduce uses the first element of the array as the default value.

solution 3 – Spread Syntax with Math.Max

const arr = [12,20,8,44,31];
const max = Math.max(...arr);

This is the shortest method, utilizing the Spread Syntax introduced in ES6.

The main concept is to spread the array into individual elements and pass them as arguments to the Math.Max function. Since the Math.Max syntax supports passing any number of arguments, this combination can be effectively used.


Conclusion


I’ve been programming for several years, focusing more on backend development. However, I’ve recently realized that there are many convenient features in JavaScript ES6 on the frontend that I haven’t explored yet, which is a bit regrettable.

Also, I’ve been studying Capture The Flag (CTF) challenges related to cybersecurity recently, and I hope to share my experiences with everyone when there’s an opportunity.

Reference

🧡You can support our team by sharing the post or clicking some ads, Thanks a lot

If you have any problem about this post, please feel free to ask~

🫵We’re also actively seeking collaboration opportunities, whether it’s through friendly links on partner sites or advertising partnerships

Some Random notes

Leave a Reply

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