I want to extract the min and max values from all of the properties of the collection:
"data": [
{
"food": 41000,
"drinks": 60,
"toys": 18961,
"candy": 8740
},
{
"food": 245,
"abusive-usage": 96,
"drinks": 5971,
"candy": 12492,
"somethingnew": 8
},
{
"food": 365,
"abusive-usage": 84,
"toys": 22605,
"candy": 9256,
"somethingold": 1
},
{}
];
Would I have known the propertyname(s) in advance, I could do something like:
const max = Math.max(...graph.datasets.urgency.map((x) => x.knownPropertyName));
Unfortunately, as I've tried to demonstrate with the example above, the properties are dynamic. I don't know in advance what property names will be in there, nor do I actually care; I only want the min and max of the values. It is safe to assume that all the values are guaranteed to be numbers.
With the following snippet I can get this to work:
let maxUrgency = 0;
let minUrgency = 0;
data.forEach((day) => {
Object.keys(day).forEach((key, index) => {
if (day[key] > maxUrgency) maxUrgency = day[key];
if (day[key] < minUrgency) minUrgency = day[key];
});
});
Although it works, it seems overly cumbersome - and probably not the most efficient - to simply use the for/forEach here. Instead, I'm looking for a more clean, vanilla approach (ES6 preferred) to achieve this. For example, a neat lambda construction based on Array.prototype perhaps. Preferably, I don't want to use a lib like lodash or underscore.
How can this piece of code be improved, ideally so I don't have to iterate through each property-for-each-item in the collection?
Related question, but definitely not the same: