Find the maximum value of a child

What would be an elegant way to find the maximum value of a child in javascript?

Example:

find the value of the maximum quantity of this object (shown as json here):

{"density":[
  {"price":1.22837, "quantity":48201},
  {"price":1.39837, "quantity":28201},
  {"price":1.40107, "quantity":127011},
  {"price":1.5174,  "quantity":75221},
  {"price":1.60600, "quantity":53271}
]}

Thank you for any advice!

PS: just to clarify: I could certainly get through, but I thought there would be a more elegant way ...

+5
source share
3 answers

The reducearray prototype method is used here :

var arr = JSON.parse(objstring)["density"];
var max = arr.reduce(function(a, b) {
   return Math.max(a, b.quantity);
}, 0);

Another solution would be something like

var max = Math.max.apply(null, arr.map(function(item){
   return item["quantity"];
}));

For more elegant ways, there are functional libraries that provide getter factory functions and other Array methods. A solution with such a library might look like

var max = arr.get("quantity").max();

which will do the same as above, but better expressed.

+9

, , , , quantity . , O (n). , (.. .)

- ...

var json = '{"density":[{"price":1.22837,"quantity":48201},{"price":1.39837,"quantity":28201},{"price":1.40107,"quantity":127011},{"price":1.5174,"quantity":75221},{"price":1.60600,"quantity":53271}]}'

var x = JSON.parse(json);
var max = 0;

x.density.forEach(function(item){
    if (item.quantity > max) max = item.quantity;
});

max

, json, .

- http://jsfiddle.net/e3dQe/

+2

max()? ...

var obj = // your object
var values = new Array();

for (key in obj) {
  values.push(obj[key])
}

var max = values.max()

, .

0

All Articles