Languages
[Edit]
EN

JavaScript - find max value in array with Array reduce method

9 points
Created by:
Krzysiek
651

In this article, we would like to show you how to find the max value in an array with the Array reduce method in JavaScript.

ECMAScript 2009 introduced Array reduce() method that helps to transform the array into different objects doing some operations on each one. In one usage case, we can find the maximum value in the array, which is very useful when we want to compare items by some nested properties.

1. Array reduce method example (ES6+)

// ONLINE-RUNNER:browser;

const array = [1, 2, 3];
const result = array.reduce((a, b) => Math.max(a, b));

console.log(result);

With nested properties:

// ONLINE-RUNNER:browser;

const array = [{value: 1}, {value: 2}, {value: 3}];
const result = array.reduce((r, b) => Math.max(r, b.value), Number.NEGATIVE_INFINITY);

console.log(result);

2. ES5 example

In ECMAScript 2009 we need to use classic function notation.

// ONLINE-RUNNER:browser;

var array = [1, 2, 3];

var result = array.reduce(function(a, b) {
    return Math.min(a, b);
});

console.log(result);

See also

  1. JavaScript - Math.max() method example

Alternative titles

  1. JavaScript - Array max value with reduce method
  2. JavaScript - how to find max value in array with Array reduce method?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join