Bug updating global arrays

HI, indeed, this unwanted behavior will happen when you try to copy an array to another array using the assignment operator (or using the flow.set like you did). In JavaScript assigning current_array to last_array will make last_array to point to the same elements of current_array, i.e, changing current_array will affect last_array and vice_versa.

var current_array = flow.get("current_array");
flow.set("last_array", current_array);
msg.payload = "set last array to current array";
return msg;

Try to use this statement to copy current_array to last_array:

last_array = [...current_array];

Only then you save last_array to the flow context

flow.set("last_array", last_array);

edit:

Therefore this is how your last function will looks like:

var current_array = flow.get("current_array");
last_array = [...current_array];
flow.set("last_array", last_array);
msg.payload = "set last array to current array";
return msg;
3 Likes