0

I have an array of json objects:

 var data = [
        {date: "12/27/2012", resolver: "Group 1", volume: 15, escalation: 90, bubble: 5},
        {date: "12/27/2012", resolver: "Group 2", volume: 85, escalation: 30,  bubble: 1},
        {date: "12/27/2012", resolver: "Group 3", volume: 130, escalation: 10,  bubble: 1},
        {date: "12/27/2012", resolver: "Group 4", volume: 240, escalation: 10,  bubble: 1}
    ];

I need to determine the max value of the "volume" field among these objects.

What is the proper syntax for this?

Eugene Goldberg
  • 11,384
  • 15
  • 81
  • 138

2 Answers2

2

try:

var data = [
        {date: "12/27/2012", resolver: "Group 1", volume: 15, escalation: 90, bubble: 5},
        {date: "12/27/2012", resolver: "Group 2", volume: 85, escalation: 30,  bubble: 1},
        {date: "12/27/2012", resolver: "Group 3", volume: 130, escalation: 10,  bubble: 1},
        {date: "12/27/2012", resolver: "Group 4", volume: 240, escalation: 10,  bubble: 1}
    ];
var max = Math.max.apply(Math, data.map(function(item) {
  return item.volume;
}));
alert(max);
jcubic
  • 51,975
  • 42
  • 183
  • 323
0

You can use the JavaScript function "sort" which takes a function as argument. This function is your sorting function, you can do what you want like that :

var data = [
      {date: "12/27/2012", resolver: "Group 1", volume: 15, escalation: 90, bubble: 5},
      {date: "12/27/2012", resolver: "Group 2", volume: 85, escalation: 30,  bubble: 1},
      {date: "12/27/2012", resolver: "Group 3", volume: 130, escalation: 10,  bubble: 1},
      {date: "12/27/2012", resolver: "Group 4", volume: 240, escalation: 10,  bubble: 1}
    ];
max = data.slice(0).sort(function(a, b) { return a.volume<b.volume })[0].volume;
alert("The max volume is : "+max);

You sort your array on the property of key "volume" and you take the first one, the one which have the greatest value for the key "volume".

The data.slice(0) is a tweak to clone an array in JavaScript, so you won't modify your initial array, if you don't care you can remove the slice(0).

Suicideboy
  • 134
  • 8