Dev Helpers
← Back

Build a voter-to-rank lookup

Build a voter-to-rank lookup. Build the result in an App Router server page and send the rendered entries to the client.

Open this example in the interactive library

Source code

// app/build-a-voter-to-rank-lookup/page.tsx
export const metadata = { title: "Build a voter-to-rank lookup" };
export default function Page() {
  const rows = [
    { name: "Ada", picks: ["A", "C", "B"] },
    { name: "Kim", picks: ["C", "A", "B"] },
    { name: "Leo", picks: ["A", "B", "C"] },
  ];
  const result = Object.fromEntries(
    rows.map((r) => [
      r.name,
      Object.fromEntries(r.picks.map((p, i) => [p, i + 1])),
    ]),
  );
  const entries = Object.entries(
    typeof result === "object" && result !== null ? result : { value: result },
  );
  return (
    <section>
      <h2>{"Build a voter-to-rank lookup"}</h2>
      {entries.length ? (
        <dl>
          {entries.map(([key, value]) => (
            <div key={key}>
              <dt>{key}</dt>
              <dd>
                {typeof value === "string" ? value : JSON.stringify(value)}
              </dd>
            </div>
          ))}
        </dl>
      ) : (
        <p>No matching entries.</p>
      )}
    </section>
  );
}