Sensor average function

Looking for solution to count avarage of ‘value’ parameter from this table:

!

currently have this code but it returns Nan error:

const val = Object.values(msg.payload)
function calculate(array) {
    return array.reduce((a, b) => a + b) / array.length;
}
msg.payload = calculate(val)
return msg;
function calculate(array) {
    return array.reduce((a, b) => a + b.value, 0) / array.length;
}
msg.payload = calculate(msg.payload)

payload is already an array

1 Like

Works now! Thank you! it returned 245.54500000000002 value, how to round it to 245.5? (found it with SMOOTH node). Thank you for your help!!!

strange, after installation NodeRED Companion (I want to create sensor for average value) it stopped working (NaN error). Even when I uninstalled Node red Companion repository... my current function looks like this:

const val = Object.values(msg.payload)
function calculate(array) {
    return array.reduce((a, b) => a + b.value, 0) / array.length;
}
msg.payload = calculate(val)
return msg;

You have messed up the function. Look again at what E1cid posted.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.