How to find the maximum and minimum in an array
Short answer
Math.max() takes separate numbers, so spread the array with ...:
const numbers = [4, 9, 2, 7];
console.log(Math.max(...numbers));
console.log(Math.min(...numbers));Output:
9
2The object with the largest value
To get the object itself rather than a number, use reduce():
const players = [
{ name: 'Anna', score: 82 },
{ name: 'Oleg', score: 95 },
];
const best = players.reduce((top, player) => (player.score > top.score ? player : top));
console.log(best.name);Output:
OlegBoth at once
One pass of reduce() can collect both the minimum and the maximum:
const temps = [12, -3, 25, 7];
const range = temps.reduce(
(acc, t) => ({ min: Math.min(acc.min, t), max: Math.max(acc.max, t) }),
{ min: Infinity, max: -Infinity },
);
console.log(range.min, range.max);Output:
-3 25Common mistake
For an empty array Math.max() returns -Infinity, and without ... it gets the whole array and returns NaN:
console.log(Math.max(...[]));
console.log(Math.max([4, 9, 2]));Output:
-Infinity
NaNFunctions used in this recipe
- Math.max — Returns the largest of the given numbers.
- Math.min — Returns the smallest of the given numbers.
- Array.prototype.reduce — Reduces an array to a single value.