Is there better way to merge 2 arrays in Node-RED

Hi Node-RED experts. Is there a “better” way of doing this with Node-RED?
I’m using 2 current state nodes to return data from 2 different HA events. Both events return an array, which I then append together.

Screenshot 2024-05-08 114833


Screenshot 2024-05-08 114730

It works, I just wondered if there is a cleaner way to achieve this?
TIA

I am far from an expert in these things, but I don’t see that there is much that can usefully make this simpler than it already is.

You are using two current state nodes that each return the given entity details. I assume that you are using Octopus Energy integration and the ‘events’ rate sensors that hold the current and next day tariff in attributes.rates

You could reduce this to just one node, and directly read the first set of rates using $entity() and the second set of rates using the $entities() function. Set just one current state node to read current rates, then set msg.payload (or whatever) to JSONata:

$append($entity().attributes.rates, $entities('event.octopus_energy_electricity_XXXXX_XXXXX_next_day_rates').attributes.rates)

This seems to work for me - $entity() does the same as setting msg.data_new to entity.

Of course, there is the moot point that Node-RED is about visibility, and using three nodes (read one array, read the other array, join both) is preferable to a bit of JSONata hidden inside the output properties of just one node. Red-Green-Refactor?

And I checked, the array appears to be already sorted in ‘start’ period order, so the sort is probably unnecessary, unless you want to reverse the order (or if you append the arrays around the wrong way).

1 Like

Hey Geoff
The $entity() function has allowed me to get rid of that unnecessary message element.
I take your point on maintaining readability, so have left it as 2 nodes.
Thanks for the advice.

Coding is very much a personal choice, and my style has changed quite a bit over the past two years of playing and learning with HA and Node-RED. I use JSONata a lot, and like reducing my top-level NR flow to a tidy and minimal set of nodes, but I also try to make the underlying code readable using code blocks, variable bindings, and comments.

I like to have meaningful, but short names to nodes, so I would probably personally go for 'Get This+Next Rates, use the one node, and if I felt it was useful, expand the JSONata to something like:

(
/* read rates from entity attributes */
    $this:=$entity().attributes.rates;
    $next:=$entities('event.octopus_energy_electricity_XXXXX_XXXXX_next_day_rates').attributes.rates;
/* combine into one array - note this does not need sorting with ^(start) */
    $append($this, $next);
)

I like a minimalist style, so use short variable names, and only use whitespace when I feel it helps. I hope that you continue to experiment with different approaches and find your own coding style that you are most comfortable with. It is, after all, your code!

1 Like