Dev Helpers
← Back

Assign points by ballot position

Assign points by ballot position. Render the transformed entries in a reusable React component.

Open this example in the interactive library

Live preview

Source code

// CollectionView.tsx
export default function CollectionView() {
  const rows = [
    { name: "Ada", picks: ["A", "C", "B"] },
    { name: "Kim", picks: ["C", "A", "B"] },
    { name: "Leo", picks: ["A", "B", "C"] },
  ];
  const result = Object.fromEntries(
    [...new Set(rows.flatMap((r) => r.picks))].map((p) => [
      p,
      rows.reduce((sum, r) => sum + r.picks.length - r.picks.indexOf(p), 0),
    ]),
  );
  const entries = Object.entries(
    typeof result === "object" && result !== null ? result : { value: result },
  );
  return (
    <section>
      <h2>{"Assign points by ballot position"}</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>
  );
}