Array of INT values

I am completely new at NODE-RED, using flows or java script functions (OK here can i a few basics). I am trying to move somewhere with my project but because i am not moving forward, i decided to ask here for an advice :slightly_smiling_face:

I am receiving data from sensor in Node-Red. i get new data every second. I managed to present it in ARRAY (values are Type INT).
i would like to make new Array: var SumArray = ; that sums incoming arrays together. For example if my incoming array is [1,1,1,1,1] i have in 5 seconds [5,5,5,5,5] (if its all the time the same ofc).

What i did is this:

var DArray = msg.payload; //incoming array of int values
var SumArray = [];

for (var i = 0; i<DArray.length;i++) {
     SumArray[i] +=  DArray[i];
msg.payload = SumArray;

return msg;

but by output is not for example [5,5,5,5,5] but [11111].

Any tips? :slight_smile:

I'm not sure I understand what you want to do.
Do you want to sum a series of messages?

i.e. msg.payload = [1,2,3,4,5]
plus msg.payload = [2,3,4,5,6]
equals msg.payload = [3,5,7,9,11]?


Exactly, but i want to sum every new message that comes every second.

You need to use a context variable to keep the values between calls to your function. Remember that the function is called again for each incoming msg, it does not maintain state between calls.

You will need to use context.get('varname'), do your summation, then use context.set.

There is a section on how to use context in the docs