Given an array of orders like this:
type Order = {
orderId: number;
customerId: number;
amount: number;
};
const orders: Order[] = [
{ orderId: 1, customerId: 1, amount: 200 },
{ orderId: 2, customerId: 2, amount: 100 },
{ orderId: 3, customerId: 1, amount: 300 },
{ orderId: 4, customerId: 3, amount: 150 },
{ orderId: 5, customerId: 2, amount: 400 },
];
- Write a function
groupOrdersByCustomer
that takes theorders
array and returns an object with the following structure:
{
1: { totalAmount: 500, orders: [1, 3] },
2: { totalAmount: 500, orders: [2, 5] },
3: { totalAmount: 150, orders: [4] }
}
- Implement it with TypeScript types (e.g.
Record<number, { ... }>
). - Add a function
getTopCustomer()
that returns thecustomerId
with the highest total spending.
Skill | Criteria |
---|---|
Array methods | Uses reduce , map , filter appropriately |
Object manipulation | Correctly accesses and updates dynamic objects |
TypeScript | Properly defines types for return value (if required) |
Logical thinking | Understands how to group and summarize data |
Clean code | Uses clear variable and function names, readable logic |
groupOrdersByCustomer(orders);
// =>
// {
// 1: { totalAmount: 500, orders: [1, 3] },
// 2: { totalAmount: 500, orders: [2, 5] },
// 3: { totalAmount: 150, orders: [4] }
// }
getTopCustomer(orders);
// => 1 or 2 (either is acceptable if totals are equal)
If you’d like more 20-minute live-coding challenges, I can provide more advanced ones like:
- Flatten a nested object
- Merge two arrays of objects by a common key
- Manually implement a
groupBy
function
Would you like a more advanced challenge next?