Dev Helpers
← Back

Count departures at each hour

Count departures at each hour. Transform the records in JavaScript and lay out the resulting entries with CSS Grid.

Open this example in the interactive library

Source code

<style>
  dl {
    display: grid;
    gap: 0.6rem;
    margin: 0;
  }
  dl > div {
    display: grid;
    gap: 0.35rem;
    padding: 0.6rem;
    border-bottom: 1px solid #bbb;
  }
  dt {
    font-weight: 700;
  }
  dd {
    margin: 0;
    overflow-wrap: anywhere;
  }
  @media (min-width: 32rem) {
    dl > div {
      grid-template-columns: minmax(5rem, 1fr) 3fr;
    }
  }
</style>
<h2>Count departures at each hour</h2>
<dl class="" id="result"></dl>
<script>
  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 = Object.fromEntries(
    [...new Set(rows.map((r) => r.start))].map((hour) => [
      hour,
      rows.filter((r) => r.start === hour).length,
    ]),
  );
  const list = document.querySelector("#result");
  list.replaceChildren();
  for (const [key, value] of Object.entries(
    typeof result === "object" && result !== null ? result : { value: result },
  )) {
    const row = document.createElement("div");
    const label = document.createElement("dt");
    label.textContent = key;
    const detail = document.createElement("dd");
    detail.textContent =
      typeof value === "string" ? value : JSON.stringify(value);
    row.append(label, detail);
    list.append(row);
  }
  if (!list.children.length) list.after("No matching entries.");
</script>