Dev Helpers
← Back

Identify the warmest station each hour

Identify the warmest station 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>Identify the warmest station each hour</h2>
<dl class="" id="result"></dl>
<script>
  const rows = [
    { site: "N", hour: 8, value: 12 },
    { site: "S", hour: 8, value: 17 },
    { site: "N", hour: 9, value: 15 },
    { site: "S", hour: 9, value: 14 },
  ];
  const result = [...new Set(rows.map((r) => r.hour))].map(
    (h) =>
      rows.filter((r) => r.hour === h).toSorted((a, b) => b.value - a.value)[0],
  );
  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>