JavaScript: GROUP BY and HAVING with Map
SQL's GROUP BY puts rows with the same key into a group and computes an aggregate for each group. WHERE filters rows before grouping, while HAVING filters the groups after the aggregate has been computed.
JavaScript
const orders = [
{ customer: "Ada", amount: 30 },
{ customer: "Bo", amount: 20 },
{ customer: "Ada", amount: 50 },
{ customer: "Cy", amount: 5 },
{ customer: "Bo", amount: 25 },
];
const totals = new Map();
for (const order of orders) {
totals.set(order.customer, (totals.get(order.customer) ?? 0) + order.amount);
}
const result = [...totals]
.filter(([, sum]) => sum >= 30)
.sort((a, b) => b[1] - a[1]);
for (const [customer, sum] of result) {
console.log(customer + " " + sum);
}