xxxxxxxxxx
// For large data, it's better to use reduce. Supose arr has a large data in this case:
const arr = [1, 5, 3, 5, 2];
const max = arr.reduce((a, b) => { return Math.max(a, b) });
// For arrays with relatively few elements you can use apply:
const max = Math.max.apply(null, arr);
// or spread operator:
const max = Math.max(arr);
xxxxxxxxxx
var values = [3, 5, 6, 1, 4];
var max_value = Math.max(values); //6
var min_value = Math.min(values); //1
xxxxxxxxxx
const myArray = [1, 14, 32, 7];
const maxValue = Math.max(myArray);
console.log(maxValue); // 32
xxxxxxxxxx
var myArray = [5, 10, 50];
Math.max(myArray); // Error: NaN
Math.max.apply(Math, myArray); // 50
xxxxxxxxxx
var numbers = [1, 2, 3, 4];
Math.max(numbers) // 4
Math.min(numbers) // 1
xxxxxxxxxx
// find maximum value of array in javascript
// array reduce method
const arr = [49,2,71,5,38,96];
const max = arr.reduce((a, b) => Math.max(a, b));
console.log(max); // 96
// math.max apply method
const max_ = Math.max.apply(null, arr);
console.log(max_); // 96
// or math.max spread operator method
const max__ = Math.max(arr);
console.log(max__); // 96
xxxxxxxxxx
function arrayMax(array) {
return array.reduce(function(a, b) {
return Math.max(a, b);
});
}
function arrayMin(array) {
return array.reduce(function(a, b) {
return Math.min(a, b);
});
}
xxxxxxxxxx
// For regular arrays:
var max = Math.max(arrayOfNumbers);
// For arrays with tens of thousands of items:
let max = testArray[0]; //here we have considered max to the first element because we don't know which is max yet.
for (let i = 1; i < testArrayLength; ++i) {
if (testArray[i] > max) { //in each iteration it will compare if the value is greater than the current considered value (we just considered first element)
max = testArray[i]; //in the above iteration if the testArray find value/element greater than max then this new max value will be considered as Max (this will happen until the max value found).
}
}