Math Max in JavaScript
Math.max simply takes a set of numbers and returns the maximum. Although it is a simple operation, it has many applications. Firstly, here is how it works:
console.log(Math.max(1, 3, 1)); // 3 const arr = [1, 3, 1]; // The spread syntax converts the array into a set of arguments // It is supported in all modern browsers except IE (but has MS Edge support) console.log(Math.max(...arr)); // 3
It works especially well when you have a list of items that convert to numbers automatically in calculations. For example, with dates which return the timestamp since 1970 in calculations:
const dates = [ new Date('2011/06/25'), new Date('2011/06/28'), new Date('2011/06/27'), new Date('2011/06/26') ]; const maxDate = new Date(Math.max(...dates)); console.log(maxDate); // 2011-06-28T04:00:00.000Z (Format varies per environment)
Combining it with maps makes working with array of objects easy:
const cars = [ { hp: 155, weight: 2400 }, { hp: 237, weight: 2465 }, { hp: 217, weight: 2000 } ]; console.log(Math.max(...cars.map((car) => car.hp))); // 237
There is one weakness with Math.max since JS and environments that implement it have argument amount limits: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply#Using_apply_and_built-in_functions. So when large amounts of data (e.g. more than 1000 items), an Array.reduce based map can be used instead:
// The 0 is the value to set the accumulator to intially const maxHp = cars.reduce((maxHp, car) => Math.max(maxHp, car.hp), 0); console.info(maxHp); // 237
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2018/mathMax.js











