- read

Max Value in an Array of Numbers in JavaScript

The Software Line 57

Photo by Radek Grzybowski on Unsplash

Sometimes, we need to find the max value inside an array of numbers.
It’s very helpful to know all the available options, so let’s start.

1. Math.max static method

This method is a composition of the static max method from Math namespace object and the spread operator. The parameter of the static method is the rest parameter, so it means that we can pass every array element as the specific argument using the spread operator.

const elements = [2, 4, 6, 8, 10, 50, 80, 120, 100];
const max = Math.max(...elements); // 100
console.log(max);

2. Sort array in ASC and get the last element

Here, we can sort the array in ascending order and then get the last element from array with Array.prototype.pop() method.
It’s important to know that the pop() method also removes the last element from the sorted (temporary) array in this case. Original array is not changed because we sorted the new array (copy from the original one).

const elements = [2, 4, 6, 8, 10, 50, 80, 120, 100];
const max = [...elements].sort((a,b)=>a-b).pop();
console.log(max); // 120

3. Reduce method from array

As we know, the purpose of Array.prototype.reduce() method is to summarize the whole array to the single value with a specific callback function which is invoked for each element of the array. So, in each iteration, we can compare the previous and the current values from the array and return the specific value based on the condition.

const elements = [2, 4, 6, 8, 10, 50, 80, 120, 100];
const max = elements.reduce((prev, curr) => prev > curr ? prev : curr, 0);
console.log(max); // 120

4. For-of loop

In this approach, we are using JavaScript function in order to calculate the maximum value. If the function input is the array of numbers we have the “for of” loop through the elements and inside each iteration we are checking if the current array element is bigger than the current maximum value and if that is the case, we are saving the max value. After all the iterations, we have the max value as the function output.


const elements = [2, 4, 6, 8, 10, 50, 80, 120, 100];
function findMaxValue(elements) {
let max = 0;
const hasNumbers = Array.isArray(elements) && elements.every(Number);
if (hasNumbers) {
for (const item of elements) {
if (item > max) {
max = item;
}
}
}

return max;
}

const max = findMaxValue(elements);
console.log(max); // 120

Conclusion

JavaScript is a versatile programming language, so, it’s really important to think about different solutions for each problem. We have four solutions to find the maximum value in an array. Using static max method is the easiest way, but it’s very useful to know also the other solutions.

Thanks for reading.
I hope you enjoyed the article and learned something.