Dev Helpers
← Back

Build price bands for repeated items

Build price bands for repeated items. 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>Build price bands for repeated items</h2>
<dl class="" id="result"></dl>
<script>
  const rows = [
    { item: "tea", units: 2, cents: 350 },
    { item: "mug", units: 1, cents: 900 },
    { item: "tea", units: 3, cents: 325 },
    { item: "tin", units: 2, cents: 500 },
  ];
  const result = Object.fromEntries(
    [...new Set(rows.map((r) => r.item))].map((item) => {
      const prices = rows.filter((r) => r.item === item).map((r) => r.cents);
      return [item, { min: Math.min(...prices), max: Math.max(...prices) }];
    }),
  );
  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>