Dev Helpers
← Back

Rank lines by their share of checkout value

Rank lines by their share of checkout value. Inspect the transformed data in the console.

Open this example in the interactive library

Source code

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 = rows
  .map((r) => ({
    item: r.item,
    sharePct: Math.round(
      (100 * r.units * r.cents) /
        rows.reduce((s, x) => s + x.units * x.cents, 0),
    ),
  }))
  .sort((a, b) => b.sharePct - a.sharePct);
console.log(JSON.stringify(result, null, 2));

Sample output

[
  {
    "item": "tin",
    "sharePct": 28
  },
  {
    "item": "tea",
    "sharePct": 27
  },
  {
    "item": "mug",
    "sharePct": 25
  },
  {
    "item": "tea",
    "sharePct": 20
  }
]