EN
JavaScript - max value in array
3
points
In this article, we would like to show you how to find maximum value in array in JavaScript.
Quick solution:
const numbers = [2, 3, 1]
const max = Math.max(...numbers)
console.log(max); // 3
1. Math.max()
In this example, we use Math.max()
method with the spread operator (...
) to find the maximum value of the numbers
array.
// ONLINE-RUNNER:browser;
const numbers = [2, 3, 1]
const max = Math.max(...numbers)
console.log(max); // 3
or:
// ONLINE-RUNNER:browser;
const array = [3, 1, 2];
const result = Math.max.apply(null, array);
console.log(result); // 3
2. Using reduce()
method
// ONLINE-RUNNER:browser;
const array = [3, 1, 2];
const result = array.reduce((a, b) => Math.min(a, b));
console.log(result); // 1
3. By comparing items
// ONLINE-RUNNER:browser;
const array = [3, 1, 2];
let result = -Infinity;
for (const item of array) {
if (item > result) {
result = item;
}
}
console.log(result); // 3
4. Add function to Array.prototype
In this example, we add a new function max()
to the Array()
object so we can use it on every array as it was a built-in function.
// ONLINE-RUNNER:browser;
var numbers = [2, 3, 1];
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
console.log(numbers.max()); // 3