HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Finding the max value of a property in an array of objects

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
propertymaxarraythefindingobjectsvalue

Problem

I'm looking for a really quick, clean and efficient way to get the max "y" value in the following JSON slice:
[
{
"x": "8/11/2009",
"y": 0.026572007
},
{
"x": "8/12/2009",
"y": 0.025057454
},
{
"x": "8/13/2009",
"y": 0.024530916
},
{
"x": "8/14/2009",
"y": 0.031004457
}
]


Is a for-loop the only way to go about it? I'm keen on somehow using Math.max.

Solution

To find the maximum y value of the objects in array:
Math.max.apply(Math, array.map(function(o) { return o.y; }))


or in more modern JavaScript:
Math.max(...array.map(o => o.y))

Warning:

This method is not advisable, it is better to use reduce. With a large array, Math.max will be called with a large number of arguments, which can cause stack overflow.

Context

Stack Overflow Q#4020796, score: 1287

Revisions (0)

No revisions yet.