Open this example in the interactive library
Source code
type Row = { item: string; units: number; cents: number };
const rows: Row[] = [
{ 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
}
]