# Loop of an array for multiple values

**URL:** https://discourse.nodered.org/t/loop-of-an-array-for-multiple-values/62234
**Category:** General
**Created:** [5 May 2022 12:25 UTC](https://discourse.nodered.org/t/loop-of-an-array-for-multiple-values/62234 "2022-05-05T12:25:16Z")
**Posts on this page:** 8
**Page:** 1

<div class="post-metadata">

### Author: ![Milanovic](https://avatars.discourse-cdn.com/v4/letter/m/3da27b/32.png) [@Milanovic](https://discourse.nodered.org/u/Milanovic)
#### Post date: [5 May 2022 12:25 UTC](https://discourse.nodered.org/t/loop-of-an-array-for-multiple-values/62234/1 "2022-05-05T12:25:17Z")

</div>

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?

---

<div class="post-metadata">

### Author: ![Blovorad](https://avatars.discourse-cdn.com/v4/letter/b/e9bcb4/32.png) [@Blovorad](https://discourse.nodered.org/u/Blovorad)
#### Post date: [5 May 2022 12:35 UTC](https://discourse.nodered.org/t/loop-of-an-array-for-multiple-values/62234/2 "2022-05-05T12:35:02Z")

</div>

Hello, with function node you can write javascript code.

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

value /= 90; // here your average

```

---

<div class="post-metadata">

### Author: ![ghayne](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/ghayne/32/39_2.png) [@ghayne](https://discourse.nodered.org/u/ghayne)
#### Post date: [5 May 2022 12:42 UTC](https://discourse.nodered.org/t/loop-of-an-array-for-multiple-values/62234/3 "2022-05-05T12:42:42Z")

</div>

Much easier in JSONata in a change node:

```auto
[
    {
        "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"
            ]
        ]
    }
]

```

---

<div class="post-metadata">

### Author: ![Barbudor](https://avatars.discourse-cdn.com/v4/letter/b/4af34b/32.png) [@Barbudor](https://discourse.nodered.org/u/Barbudor)
#### Post date: [5 May 2022 12:43 UTC](https://discourse.nodered.org/t/loop-of-an-array-for-multiple-values/62234/4 "2022-05-05T12:43:25Z")

</div>

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":[]}]
```

---

<div class="post-metadata">

### Author: ![E1cid](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/e1cid/32/77971_2.png) [@E1cid](https://discourse.nodered.org/u/E1cid)
#### Post date: [5 May 2022 16:04 UTC](https://discourse.nodered.org/t/loop-of-an-array-for-multiple-values/62234/5 "2022-05-05T16:04:22Z")

</div>

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

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

```

---

<div class="post-metadata">

### Author: ![Milanovic](https://avatars.discourse-cdn.com/v4/letter/m/3da27b/32.png) [@Milanovic](https://discourse.nodered.org/u/Milanovic)
#### Post date: [6 May 2022 06:02 UTC](https://discourse.nodered.org/t/loop-of-an-array-for-multiple-values/62234/6 "2022-05-06T06:02:25Z")

</div>

How can I do it for an array like this on an easy way?  
 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/c/f/cf7e0a7228b657c0ffd71ff63e4bdad20bb6f111.png)

---

<div class="post-metadata">

### Author: ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)
#### Post date: [6 May 2022 07:07 UTC](https://discourse.nodered.org/t/loop-of-an-array-for-multiple-values/62234/7 "2022-05-06T07:07:12Z")

</div>

> [@Milanovic](#):
>
> How can I do it for an array like this

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

```auto
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 🙂 ...

There’s a great page in the docs ([Working with messages : Node-RED](https://nodered.org/docs/user-guide/messages)) 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](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/b/d/bd1f333a9e043b061b39917c328b0094d3e52d30.gif)

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

 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/5/4/5400f7a8b9eb042aeba05c642ee99a7e7de674c4.png)

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

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)
#### Post date: [5 July 2022 07:07 UTC](https://discourse.nodered.org/t/loop-of-an-array-for-multiple-values/62234/8 "2022-07-05T07:07:49Z")

</div>

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