Dev Helpers
← Back

Calculate the first-to-last change per site

Calculate the first-to-last change per site. Transform the records in JavaScript and present the entries with Tailwind utilities.

Open this example in the interactive library

Source code

<h2>Calculate the first-to-last change per site</h2>
<dl
  class="grid gap-2 p-4 rounded-lg bg-stone-100 text-stone-900"
  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 = Object.fromEntries(
    [...new Set(rows.map((r) => r.site))].map((site) => {
      const a = rows
        .filter((r) => r.site === site)
        .toSorted((x, y) => x.hour - y.hour);
      return [site, a[a.length - 1].value - a[0].value];
    }),
  );
  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");
    row.className = "grid gap-1 border-b border-stone-300 py-2 sm:grid-cols-2";
    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>