JS Built-ins
← Array151 / 226
ArrayArray.prototype.reduceintermediate

Array.prototype.reduce() β€” find the maximum value

πŸ“– Usage Example
const nums = [3, 1, 4, 1, 5, 9]
nums.reduce((max, n) => n > max ? n : max, -Infinity)
// β†’ 9

Use reduce() to find the maximum value by updating the accumulator when a larger value is found.

Finding max with reduce

You can find the maximum value in an array using reduce() β€” without Math.max.

[3, 1, 4, 1, 5, 9].reduce((max, cur) => cur > max ? cur : max, -Infinity) // 9
πŸ’‘ Hints (3)
  • β€’ Use `-Infinity` as the initial value so any real number beats it.
  • β€’ The reducer is `(max, cur) => cur > max ? cur : max`.
  • β€’ Do not use `Math.max` β€” solve it purely with `reduce`.