3

I have code that finds the max of two properties, but I don't know that it's the best way to do this. I am inside jQuery's $.getJSON(URI, function(json){}) call.

The goal is to make a bar chart with 2 bars that's exactly the width of the longest bar.

Currently to find the maximum value:

var max = Math.max.apply(this, $.map(json, function(d){ return Math.max(d.bar1, d.bar2); })); 

Is there a better way?

Edit: A json string, as requested:

[ { "bar1": "15", "bar2": "13" }, { "bar1": "20", "bar2": "25" }, { "bar1": "10", "bar2": "18" } ] 

max should be equal to 25 with this as an input.

1
  • Your problem does not have anything to do with JSON. Once it is parsed you are working with JavaScript objects. Commented Sep 27, 2012 at 18:20

1 Answer 1

3

This works, and is marginally shorter, albeit not necessarily more efficient:

var max = json.reduce(function(p, d) { // p is the current max return Math.max(p, d.bar1, d.bar2); }, 0); 

See http://jsfiddle.net/PF8Me/1/

Note that it does assume that all of your values are positive (hence the "initial value" of zero supplied to reduce).

Use a shim for Array.reduce if you're not using an ES5 browser.

Sign up to request clarification or add additional context in comments.

3 Comments

@Caleb and for not needing jQuery ;-)
Curious, why don't people like jQuery? I've seen that sentiment all over stack overflow.
@Caleb actually I use jQuery all the time. I was mostly referring to using standard ES5 functions (e.g. reduce, map) instead of $.map.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.