Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the max value of an attribute in an array of objects

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.

like image 201
Rio Avatar asked Oct 26 '10 04:10

Rio


People also ask

How do you find the max value in an array in Java?

Method 4: Using Collections.max() Define an empty ArrayList and add all elements of array to it. Pass this ArrayList to Collections. max(). The max() method of java.

How do you find the max value in an array in Python?

Python Numpy – Get Maximum Value of Array Given a numpy array, you can find the maximum value of all the elements in the array. To get the maximum value of a Numpy Array, you can use numpy function numpy. max() function.


2 Answers

To find the maximum y value of the objects in array:

Math.max.apply(Math, array.map(function(o) { return o.y; })) 
like image 103
tobyodavies Avatar answered Sep 18 '22 14:09

tobyodavies


Find the object whose property "Y" has the greatest value in an array of objects

One way would be to use Array reduce..

const max = data.reduce(function(prev, current) {     return (prev.y > current.y) ? prev : current }) //returns object 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce http://caniuse.com/#search=reduce (IE9 and above)

If you don't need to support IE (only Edge), or can use a pre-compiler such as Babel you could use the more terse syntax.

const max = data.reduce((prev, current) => (prev.y > current.y) ? prev : current) 
like image 28
Andy Polhill Avatar answered Sep 22 '22 14:09

Andy Polhill