Javascript ECMAScript-2021 Minimum of average value over time between group items

Hi @all.
I’m searching for the most efficient way in getting the smallest value of the average value of all items in a group over time.
The items are getting persited on every update and every change in InfluxDB2.
Example:
I have a group of three items:
group

  • number item1
  • number item2
  • number item3

What i have now is getting every average value in a separate variable and searching for the minimum.
Is there a more dynamic way getting the value without naming every group item?

var now     = time.ZonedDateTime.now();
var item1   = items.getItem("item1").history.averageSince(now.minusDays(7), "influxdb");
var item2   = items.getItem("item2").history.averageSince(now.minusDays(7), "influxdb");
var item3   = items.getItem("item3").history.averageSince(now.minusDays(7), "influxdb");
var minimum = Math.min(item1, item2, item3);
console.log("Minimum: " + minimum);

Every hint is very welcome!

Hi,
I would start with something like this:

var minValue = Number.MAX_VALUE;
items.getItem("groupName").members.forEach(function(it) {
  var itemAvg = it.history.averageSince(time.ZonedDateTime.now().minusDays(7), "influxdb");
  if (minValue > itemAvg) minValue = itemAvg;
});
console.log("Minimum: " + minValue);

I’m not sure any way is going to be better or worse.

You could get fancy and use a map/reduce.

var minimum = items.GroupName.members.map( item => item.history.averageSince(time.toZDT('P-7D'))
                                     .reduce((min, curr) => (curr < min) ? min : curr, Number.MAX_VALUE);
console.log("Minimum: " + minimum);

Or combine your approach with a map like above instead of the reduce.

var minimum = Math.min(items.GroupName.members.map( item => item.history.averageSince(time.toZDT('P-7D'));
console.log("Minimum: " + minimum);

Note that it is shorter to take advantage of time.toZDT(). If you need now it’s shorter to use time.toZDT(). If you want some time in the past or future, it can be more clear and certainly shorter to use an ISO8601 duration string. P-7D is minus seven days. One hour two minutes forward is PT1H2M.

1 Like

Sorry for my late response and thanks @djal and @rlkoshak for your advise!
The approach with a forEach loop is nice, i had that now for a week but was getting ambitious shrinking my code down.
The second approach with a Math.min function didn’t work at first because of the missing three dots at the beginning. I can’t mark any attempt as solution because every attempt is correct.
My code looks like this now:

var minValue = Math.min(...items.getItem("GROUPNAME").members.map( item => item.history.averageSince(time.toZDT('P-7D'))));
console.log("Minimum: " + minValue);