Get the Max number of an Array in JavaScript
Get the Max number of an Array
To get the max number of an array, we can use the Math.max() method by passing the array of elements as a argument to it . It returns the max number from the array.
Here is an example:
const arr = [2, 4, 55, 34, 12];
const maxNumber = Math.max(...arr);
console.log(maxNumber);
Output:
55
In the example above, we have used the Math.max(..arr)
to get the max number of an array.
The Math.max() method accepts only the individual values but not an array, so we unpacked the array by using the es6 (…) spread operator and passed to it.
We can also call Math.max() method without unpacking the array by using the Function.prototype.appl().
Here is an example:
const arr = [2, 4, 55, 34, 12];
const maxNumber = Math.max.apply(null, arr);
console.log(maxNumber);