Dev Helpers
← Back

Transpose ballots into rank columns

Transpose ballots into rank columns. Parse newline-delimited records from a readable stream before applying the transformation.

Open this example in the interactive library

Source code

import { Readable } from "node:stream";
import { createInterface } from "node:readline";
const input = Readable.from([
  '{"name":"Ada","picks":["A","C","B"]}\n',
  '{"name":"Kim","picks":["C","A","B"]}\n',
  '{"name":"Leo","picks":["A","B","C"]}\n',
]);
const rows = [];
for await (const line of createInterface({ input, crlfDelay: Infinity })) {
  rows.push(JSON.parse(line));
}
const result = rows[0].picks.map((_, i) => rows.map((r) => r.picks[i]));
console.log(JSON.stringify(result, null, 2));

Sample output

[
  [
    "A",
    "C",
    "A"
  ],
  [
    "C",
    "A",
    "B"
  ],
  [
    "B",
    "B",
    "C"
  ]
]