Course contentsShow
← JavaScript
Lesson 462 of 2,72312. Higher-Order FunctionsFree lesson

Reduce for Finding Max or Min

Using reduce to find the maximum or minimum value in an array by comparing accumulator and current.

Reduce for Finding Max or Min

You'll learn how to use reduce to find the largest or smallest value in an array by comparing the accumulator against each element.

The Core Idea

When finding a maximum or minimum value, you're essentially asking: "What's the biggest (or smallest) number I've seen so far?" That's exactly what reduce excels at—it lets you carry forward a "best so far" value (the accumulator) and update it as you examine each element.

The pattern is simple: your reducer function compares the accumulator (current best) with the current element, then returns whichever is larger (for max) or smaller (for min).

Finding the Maximum

const numbers = [3, 9, 2, 15, 7];

const max = numbers.reduce((accumulator, current) => {
  return current > accumulator ? current : accumulator;
});

console.log(max); // 15

Here, the accumulator starts at 3 (first element, since no initial value provided). Each iteration asks: "Is current bigger than what I've seen?" If yes, it becomes the new accumulator.

Finding the Minimum

const numbers = [12, 5, 8, 3, 19];

const min = numbers.reduce((accumulator, current) => {
  return current < accumulator ? current : accumulator;
});

console.log(min); // 3

Same logic, but we keep the smaller value instead.

With Math Functions

You can also use Math.max or Math.min:

const numbers = [4, 22, 9, 14];

const max = numbers.reduce((acc, curr) => Math.max(acc, curr));
const min = numbers.reduce((acc, curr) => Math.min(acc, curr));

Key Takeaway: Use reduce to find max or min by comparing the accumulator with each element and returning the "winner" at each step—it's like carrying forward the best candidate you've found so far.