Languages
[Edit]
EN

JavaScript - how to find max value in array with Array reduce method?

9 points
Created by:
Kate_C
2895

ECMAScript 2009 introduced Array reduce() method that helps to transform array to different object doing some operations on each one element. As one usage case we can find maximum value in array, that is verry useful when we want to compare items by some nested properties.

1. ES 6 and newests example

In ECMAScript 2015 we can use arrow functions that makes code more clear.

// 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. ES 5 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.max(a, b);
});

console.log(result);

See also

  1. JavaScript - Math.max() method example
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.