EN
JavaScript - find max value in array with Array reduce method
9
points
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);