Programs & Examples
Objects · Study material
Group orders by city
An object used as a dictionary: ??= creates each city's group the first time it appears, and Object.entries prints the groups in insertion order.
// Group orders by city and total them – objects as dictionaries
const orders = [
{ id: 1, city: "Pune", amount: 1200 },
{ id: 2, city: "Delhi", amount: 800 },
{ id: 3, city: "Pune", amount: 450 },
{ id: 4, city: "Chennai", amount: 999 },
{ id: 5, city: "Delhi", amount: 300 },
];
const byCity = {};
for (const { city, amount } of orders) {
byCity[city] ??= { orders: 0, total: 0 }; // create the group the first time
byCity[city].orders++;
byCity[city].total += amount;
}
for (const [city, { orders: n, total }] of Object.entries(byCity)) {
console.log(`${city.padEnd(8)} ${n} orders ₹${total}`);
}
Pune 2 orders ₹1650 Delhi 2 orders ₹1100 Chennai 1 orders ₹999
Transforming an object
The keys/values/entries example on the Introduction tab shows the entries → map → fromEntries pattern for building a changed copy of an object.