Open this example in the interactive library
Source code
import { Readable } from "node:stream";
import { createInterface } from "node:readline";
const input = Readable.from([
'{"item":"tea","units":2,"cents":350}\n',
'{"item":"mug","units":1,"cents":900}\n',
'{"item":"tea","units":3,"cents":325}\n',
'{"item":"tin","units":2,"cents":500}\n',
]);
const rows = [];
for await (const line of createInterface({ input, crlfDelay: Infinity })) {
rows.push(JSON.parse(line));
}
const result = Object.fromEntries(
rows.toSorted((a, b) => b.cents - a.cents).map((r) => [r.item, r.cents]),
);
console.log(JSON.stringify(result, null, 2));
Sample output
{
"mug": 900,
"tin": 500,
"tea": 325
}