Open this example in the interactive library
Source code
import { Readable } from "node:stream";
import { createInterface } from "node:readline";
const input = Readable.from([
'{"site":"N","hour":8,"value":12}\n',
'{"site":"S","hour":8,"value":17}\n',
'{"site":"N","hour":9,"value":15}\n',
'{"site":"S","hour":9,"value":14}\n',
]);
const rows = [];
for await (const line of createInterface({ input, crlfDelay: Infinity })) {
rows.push(JSON.parse(line));
}
const result = [...new Set(rows.map((r) => r.site))].flatMap((site) => {
const a = rows.filter((r) => r.site === site);
return a
.slice(1)
.map((r, i) => ({ site, previous: a[i].value, current: r.value }));
});
console.log(JSON.stringify(result, null, 2));
Sample output
[
{
"site": "N",
"previous": 12,
"current": 15
},
{
"site": "S",
"previous": 17,
"current": 14
}
]