I have just figured out some great way to find the min and max value from the array and I just wanted to share with all of you.
See the code below, use it or add console log to understand it in depth.
var arr = [12, 89, 67, 55];
// Method 1
function arrayMax(arr) {
return arr.reduce(function(p, v) {
return Math.max(p, v); // Math.min for min
});
}
arrayMax(arr);
// Method 2
function arrayMax(arr) {
return arr.reduce(function(p, v) {
return p > v ? p : v; // p < v for min
});
}
arrayMax(arr);
// Method 3
Math.max(...arr); // Math.min for min
// Method 4
function findMinMax(arr) {
let min = arr[0],
max = arr[0];
for (let i = 1, len = arr.length; i < len; i++) {
let v = arr[i];
min = v < min ? v : min;
max = v > max ? v : max;
}
return [min, max];
}
findMinMax(arr);
0 on: "Find the min/max element of an Array in JavaScript"