Dev Helpers
← Back

Rank routes by total service hours

Rank routes by total service hours. 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 = [
    { line: "Red", start: 8, end: 10 },
    { line: "Blue", start: 9, end: 11 },
    { line: "Red", start: 12, end: 15 },
    { line: "Gold", start: 15, end: 16 },
  ];
  const result = [...new Set(rows.map((r) => r.line))]
    .map((line) => ({
      line,
      hours: rows
        .filter((r) => r.line === line)
        .reduce((sum, r) => sum + r.end - r.start, 0),
    }))
    .sort((a, b) => b.hours - a.hours);
  const entries = Object.entries(
    typeof result === "object" && result !== null ? result : { value: result },
  );
  return (
    <section>
      <h2>{"Rank routes by total service hours"}</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>
  );
}