Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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
2

The 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:

Oleg

Both 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 25

Common 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
NaN

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.