find max value of a child object

2019-04-09 09:04发布

问题:

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

Example:

find the max quantity value of this object (here shown as 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}
]}

thank you for any advice!

PS: just to clarify: of course i could loop through, but i thought there would be a more elegant way ...

回答1:

There's the reduce method of the Array prototype:

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 which provide getter factory functions and more Array methods. A solution with such a library could look like

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

which would do exactly the same as the above one, but nicer expressed.



回答2:

There is no way other than looping thru, because you need to visit every child in order to see if the quantity parameter is the new max. In other words, the complexity of the problem is O(n). If the children were ordered by quantity, it would be a different story (i.e. just get the first or last child in the list.)

something like the following...

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;
});

After this runs, max is the max quantity

note you didn't give us correct json, so I tweaked it a bit.

Here is an example -- click run and look in your console http://jsfiddle.net/e3dQe/



回答3:

How about the max() method? But first you would need to collect all the values in an array...

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

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

var max = values.max()

Not much more elegant, but a different solution.