views:

20

answers:

2

Hi all!

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...

Thanks!

+3  A: 
Math.max.apply(null,array.map(function(o){return o.y;}))
tobyodavies
A: 

Well, first you should parse the JSON string, so that you can easily access it's members:

var arr = $.parseJSON(str);

Use the map method to extract the values:

arr = $.map(arr, function(o){ return o.y; });

Then you can use the array in the max method:

var highest = Math.max.apply(this,arr);

Or as a one-liner:

var highest = Math.max.apply(this,$.map($.parseJSON(str), function(o){ return o.y; }));
Guffa