How-to
Build a self-sorting active-pump list in Node-RED
Short answer
Keep each pump as an index-timestamp pair in flow context, stamp new Date().getTime() on every false-to-true transition and zero it on the way down. Sort the pairs by decreasing time to build the display writes, then restore index order before the next scan. Use the timestamp design when several active pumps must stay visible in recency order; use the radio-button pattern when only the latest selection matters.

On this page
- What tables does the self-sorting list need?
- How do I record the activation time on each rising edge?
- How do I sort by time without losing the pump index?
- How do I write the sorted order into the display tables?
- Why must the pairs go back into index order?
- When is the radio-button shortcut enough?
- Does the timestamp list survive a Node-RED restart?
- How do I verify the finished flow?
- Questions asked
A self-sorting pump list needs one data structure and three rules. Keep every pump as an index-timestamp pair in flow context, stamp new Date().getTime() on each false-to-true transition, zero the stamp on the way back down, then sort a copy by decreasing time to build the display. The flow below does it for ten pumps on a 0.5 s scan with two Function nodes, an RBE node and a Split node, so the most recently activated pump always sits at the top of the display — and a stripped-down radio-button variant covers the case where only the latest selection should stay active.
What tables does the self-sorting list need? #
Three tables in the data store and one flow-context array: a Boolean button table of length 10 that receives the pump states, a number table that shows pump numbers, a text table that shows status strings, and a flow-context array holding one index-timestamp pair per pump. This example uses the names below; your data store can use any names, as long as the write objects carry the same ones.
| Name | Kind | Role |
|---|---|---|
dynamic_buttons |
Boolean table, length 10 | The ten pump buttons, read as one array. |
dynamic_number |
Display table | Pump numbers, most recent first. |
dynamic_text |
Display table | Activation time or Pump disabled. |
btn_times |
Flow context | The [index, timestamp] pairs. |
The display page shows the ten buttons plus two columns of ten text fields each, one column bound to the number table and one to the text table. Node-RED never touches the fields themselves: it reads the button table and writes the two display tables.
How do I record the activation time on each rising edge? #
An Inject node fires every 0.5 s, the read node returns the whole Boolean table, an RBE node passes it only when a value has changed, and a Function node stamps new Date().getTime() into any pair whose button just went from false to true. Wire the scan chain in this order:
- An Inject node repeating every 0.5 s.
- A data-store read node returning
dynamic_buttonswith table length 10 intomsg.payload. - An RBE node watching
msg.payload, in the plain block-unless-value-changes mode. - The Function node named
save button press time. - The Function node named
order data by time. - A Split node with array split length 1.
- The data-store write node.
The first Function node keeps the pairs in flow context:
// Function node: "save button press time"
const count = 10; // number of pumps
let timestamps = flow.get('btn_times') || []; // our array; flow.get is the Node-RED API
if (timestamps.length < 1) {
for (let i = 0; i < count; i++) timestamps.push([i, 0]); // pairs of [index, timestamp]
}
for (let i = 0; i < msg.payload.length; i++) {
if (msg.payload[i] && timestamps[i][1] === 0) { // OFF -> ON
timestamps[i] = [i, new Date().getTime()];
} else if (!msg.payload[i] && timestamps[i][1] > 0) { // ON -> OFF
timestamps[i] = [i, 0];
}
}
flow.set('btn_times', timestamps);
return { payload: timestamps };
The RBE node passes the table only when its value changes, so the processing path runs on real transitions instead of on every scan. Keep the plain mode: with the ignore-initial-value variant the first table after a deploy is held back for comparison only, and the list stays empty until something toggles. In plain mode that first read seeds the pairs for pumps that are already on.
A pump that stays on keeps its first stamp, because the code only writes when the saved stamp is zero. A stamp of zero is the off marker.
How do I sort by time without losing the pump index? #
Sort the outer array of pairs with the comparator b[1] - a[1]; because each pair moves as one unit, row i after the sort still carries its zero-based pump index in element 0 and its activation stamp in element 1. That is the same keep-key-and-value-in-one-element device you use to build multidimensional arrays in Node-RED for InfluxDB writes: nothing that reorders or stores the array can separate a pump from its time.
Take an example run. Pump 8 — index 7 — turns on first, and pump 5 — index 4 — turns on second. To keep the arithmetic readable, the stamps below are written as milliseconds after midnight; real stamps from new Date().getTime() are milliseconds since the epoch, and the subtraction works the same.
- Pair A:
[7, 463250000]— pump 8 on at 46 325 s, which is 12:52:05. - Pair B:
[4, 467720000]— pump 5 on at 46 772 s, which is 12:59:32. - The other eight pairs carry zero stamps.
The comparator computes 467 720 000 − 463 250 000 = 447 000, a positive result, so B is ordered before A: pump 5 takes display position 0 and pump 8 takes position 1. The gap of 447 000 ms is 447 s, or 7 minutes 27 seconds — exactly the lead pump 5 gets. The zero-stamp pairs sort below both.
Prove the sort before deploying, in any JavaScript console:
const pairs = [[7, 463250000], [4, 467720000]]; // example input
pairs.sort(function (a, b) { return b[1] - a[1]; });
// pairs is now [[4, 467720000], [7, 463250000]]
Those two lines are the whole sort, and they show the pair surviving the reorder.
How do I write the sorted order into the display tables? #
Loop over the sorted array and push two write objects per row — one for dynamic_number carrying the index plus one, one for dynamic_text carrying the time string — then pass the object array through the Split node. This is the second Function node in full:
// Function node: "order data by time"
const timestamps = msg.payload; // the pair array from "save button press time"
timestamps.sort(function (a, b) { return b[1] - a[1]; }); // newest stamp first
const objects = []; // write objects, starts empty
for (let i = 0; i < timestamps.length; i++) {
if (timestamps[i][1] > 0) { // active pump
objects.push({ tagName: 'dynamic_number', tableStartIndex: i, values: timestamps[i][0] + 1 });
const myTime = new Date(timestamps[i][1]).toString();
objects.push({ tagName: 'dynamic_text', tableStartIndex: i, values: myTime.substring(4, myTime.length - 15) });
} else { // inactive row
objects.push({ tagName: 'dynamic_number', tableStartIndex: i, values: 0 });
objects.push({ tagName: 'dynamic_text', tableStartIndex: i, values: 'Pump disabled.' });
}
}
timestamps.sort(function (a, b) { return a[0] - b[0]; }); // back to index order
return { payload: objects };
Each object names its target table in tagName, its row in tableStartIndex and its value in values. Two objects per row makes 2 × 10 = 20 objects per pass, and the Split node with array split length 1 turns them into 20 messages, one per object. The write node runs in dynamic mode: it takes the tag name and table position from each message and writes payload.values as the value.
Never hand the whole object array to a node that expects one value per message. A node built that way writes only the last element of an array — the failure mode behind why InfluxDB keeps only the last record of a Node-RED array write. The Split node is what prevents that here.
Why must the pairs go back into index order? #
Because the next scan compares msg.payload[i] against timestamps[i] by button position: if the array stayed in time order, button i would be checked against another pump's stamp and the list would corrupt itself within one scan. Array sort reorders in place, and the array the second node receives is the same array object the first node saved in flow context, so a time-ordered array would still be time-ordered when the next read arrives.
The closing sort with the index comparator, a[0] - b[0], repairs the order after the write objects have captured the display sequence. The objects carry their own copies of position and value, so restoring afterwards changes nothing on the display. Never delete that line.
When is the radio-button shortcut enough? #
When the requirement is only that the latest selected pump stays on and every other one turns off, drop the timestamps entirely: on each new false-to-true transition, write true at that index and false at every other index of the same Boolean array. No flow-context pairs, no sort and no write objects — the state table itself is the whole design.
For a PLC integer table, replace true and false with 1 and 0 and send the complete array in one message straight to the write node, which eliminates both the write objects and the Split node; do that only where the write node accepts a whole table in one message. The decision: if several active pumps must stay visible in recency order, build the timestamp design; if only the newest selection may be active, the radio-button pattern is the whole job.
Does the timestamp list survive a Node-RED restart? #
No, not with default settings: context is stored in memory only and is cleared whenever Node-RED restarts, so every pair comes back as zero and each pump still running is re-stamped as newly activated on the first scan. Since release 0.19, Node-RED can store node, flow and global context in a file that persists over restarts, configured in the settings file.
With file-backed context the stamps survive; without it, the recency order restarts from whatever toggles after the boot. Either way, treat the list as an operator view, not a record of when pumps started, and never feed the re-sorted display into a permissive or sequence decision — that is the one rule to keep.
How do I verify the finished flow? #
Five checks on the display prove the flow: one pump alone, a second on top of it, one turned off, an idle stretch, and a sweep of all ten positions.
- Turn on one pump. Its number takes the top row of the number table with a real time string beside it.
- Turn on a second pump. It takes the top row; the first pump moves down one row and keeps its original time.
- Turn one of them off. It leaves the active rows, and its slot shows 0 with
Pump disabled. - Leave every button untouched through several scans. The RBE node blocks and nothing downstream executes — confirm on the debug sidebar.
- Toggle each of the ten buttons in turn. Displayed numbers run 1 to 10 while the pairs keep indexes 0 to 9.
- Restart Node-RED with pumps running. With default memory context the active pumps are re-stamped; with file-backed context the original times return. In both cases the list must rebuild without manual intervention.
If all six pass, the list is doing exactly what the pattern promises: active pumps in activation order, cleared rows for the rest, and no writes when nothing changed.
Questions asked
How do I scale the list past ten pumps?
Raise the count constant in the save function, set the read node's table length to the same number, and add one text field pair per row on the display. Every row adds two write objects per pass, so twenty pumps push forty objects through the split node whenever the order changes.
Why write a zero and a disabled label instead of skipping inactive rows?
Display tables keep whatever was written last. A pass that wrote only the active rows would leave the number and time of a pump that just turned off sitting in a lower slot, so an operator would read a stopped pump as running. Writing every row on every pass is what keeps the list truthful.
Can the same pattern drive an alarm list?
Yes. Any Boolean table works: stamp each false-to-true transition and the active items order themselves by recency. Treat it as an operator view, not an event log, because the times are display state and whatever is still active gets re-stamped after a restart.
What does the substring cut from the time string?
It trims the leading weekday and the trailing time-zone text from the string the JavaScript date object produces, so each row shows a compact local date and time. The exact characters depend on how your runtime formats that string, so confirm the cut points on your own install.

