TypingKit
← Code

JavaScript: Group items by a key

Written for TypingKit · ~2 min

0 wpm 100% accuracy 100% real accuracy
const orders = [↵
{ id: 1, city: "Boston", total: 42.5 },↵
{ id: 2, city: "Denver", total: 18.0 },↵
{ id: 3, city: "Boston", total: 7.25 },↵
];↵
↵
const byCity = orders.reduce((groups, order) => {↵
(groups[order.city] ??= []).push(order);↵
return groups;↵
}, {});↵
↵
for (const [city, list] of Object.entries(byCity)) {↵
const sum = list.reduce((a, o) => a + o.total, 0);↵
console.log(`${city}: ${list.length} orders, $${sum.toFixed(2)}`);↵
}