Loop of an array for multiple values

Hello,

I have an array of 90 values and know I want to calculate the avarage value of all that values.
Is it possible to write it with a loop? How would you do it?

Hello, with function node you can write javascript code.

value = 0;
for(let i=0; i < array.length; i++){
    value += array[i];
}

value /= 90; // here your average

Much easier in JSONata in a change node:

[
    {
        "id": "67dbbd0a1289b707",
        "type": "inject",
        "z": "92b229f221db59a2",
        "name": "",
        "props": [
            {
                "p": "payload"
            },
            {
                "p": "topic",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "[1,2,3,4]",
        "payloadType": "jsonata",
        "x": 170,
        "y": 80,
        "wires": [
            [
                "cbd0bd2089376d85"
            ]
        ]
    },
    {
        "id": "7578bc3be62babd3",
        "type": "debug",
        "z": "92b229f221db59a2",
        "name": "",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "false",
        "statusVal": "",
        "statusType": "auto",
        "x": 570,
        "y": 80,
        "wires": []
    },
    {
        "id": "cbd0bd2089376d85",
        "type": "change",
        "z": "92b229f221db59a2",
        "name": "",
        "rules": [
            {
                "t": "set",
                "p": "payload",
                "pt": "msg",
                "to": "$average(payload)\t",
                "tot": "jsonata"
            }
        ],
        "action": "",
        "property": "",
        "from": "",
        "to": "",
        "reg": false,
        "x": 340,
        "y": 80,
        "wires": [
            [
                "7578bc3be62babd3"
            ]
        ]
    }
]
2 Likes

Assuming that you have that array in the payload of a single message I see 2 possibilities
See below

[{"id":"ba105eae32da85ae","type":"tab","label":"Flow 1","disabled":false,"info":"","env":[]},{"id":"da182adb95eba196","type":"inject","z":"ba105eae32da85ae","name":"Array","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"[1, 6, 9, 10, 33, 78]","payloadType":"json","x":150,"y":200,"wires":[["add5649e81836764","475a185673dd188e"]]},{"id":"add5649e81836764","type":"function","z":"ba105eae32da85ae","name":"Average","func":"var sum = 0.0;\nvar count = 0;\nmsg.payload.forEach( item => {\n    sum += item;\n    count += 1;\n})\nmsg.payload = sum/count;\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":340,"y":140,"wires":[["01efa64e381505ef"]]},{"id":"01efa64e381505ef","type":"debug","z":"ba105eae32da85ae","name":"Function result","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":620,"y":140,"wires":[]},{"id":"475a185673dd188e","type":"split","z":"ba105eae32da85ae","name":"","splt":"\\n","spltType":"str","arraySplt":1,"arraySpltType":"len","stream":false,"addname":"","x":330,"y":240,"wires":[["3d51bc9152425d97"]]},{"id":"3d51bc9152425d97","type":"join","z":"ba105eae32da85ae","name":"","mode":"reduce","build":"object","property":"payload","propertyType":"msg","key":"topic","joiner":"\\n","joinerType":"str","accumulate":true,"timeout":"","count":"","reduceRight":false,"reduceExp":"$A+payload","reduceInit":"0","reduceInitType":"num","reduceFixup":"$A/$N","x":450,"y":240,"wires":[["b064d51f0f640ad6"]]},{"id":"b064d51f0f640ad6","type":"debug","z":"ba105eae32da85ae","name":"Split/Join result","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":620,"y":240,"wires":[]}]

@ghayne is the simplest solution, but if you want to use JS array.reduce() would be my preferred method.

const count = msg.payload.length;
msg.payload = msg.payload.reduce((acc, number) => acc += number, 0)/count
return msg;
2 Likes

How can I do it for an array like this on an easy way?
image

By using the solution @E1cid offered and accessing the element [1] of the payload e.g.

const count = msg.payload[1].length;
msg.payload = msg.payload[1].reduce((acc, number) => acc += number, 0)/count
return msg;

Canned text - to help you help yourself :slight_smile: ...

There’s a great page in the docs (Working with messages : Node-RED) that will explain how to use the debug panel to find the right path to any data item.

Pay particular attention to the part about the buttons that appear under your mouse pointer when you over hover a debug message property in the sidebar.

BX00Cy7yHi

So in your case, you would have clicked the Copy Path button for the this item ...
image

That would have put payload[1] onto your clipboard - letting you know the path to the element of interest.

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