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:
xxxxxxxxxx
1
const numbers = [2, 3, 1]
2
3
const max = Math.max(numbers)
4
5
console.log(max); // 3
In this example, we use Math.max()
method with the spread operator (...
) to find the maximum value of the numbers
array.
xxxxxxxxxx
1
const numbers = [2, 3, 1]
2
3
const max = Math.max(numbers)
4
5
console.log(max); // 3
or:
xxxxxxxxxx
1
const array = [3, 1, 2];
2
3
const result = Math.max.apply(null, array);
4
5
console.log(result); // 3
xxxxxxxxxx
1
const array = [3, 1, 2];
2
3
const result = array.reduce((a, b) => Math.min(a, b));
4
5
console.log(result); // 1
xxxxxxxxxx
1
const array = [3, 1, 2];
2
3
let result = -Infinity;
4
5
for (const item of array) {
6
if (item > result) {
7
result = item;
8
}
9
}
10
11
console.log(result); // 3
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.
xxxxxxxxxx
1
var numbers = [2, 3, 1];
2
3
Array.prototype.max = function() {
4
return Math.max.apply(null, this);
5
};
6
7
console.log(numbers.max()); // 3