Skip to content

Instantly share code, notes, and snippets.

@charlie-goldenowl
Created May 23, 2025 09:58
Show Gist options
  • Save charlie-goldenowl/ef0bfaf24213e01a2637f84023427f7e to your computer and use it in GitHub Desktop.
Save charlie-goldenowl/ef0bfaf24213e01a2637f84023427f7e to your computer and use it in GitHub Desktop.
Group Orders by Customer.md

💡 Problem: Group Orders by Customer

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 },
];

✅ Requirements:

  1. Write a function groupOrdersByCustomer that takes the orders 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] }
}

🎯 Bonus (optional):

  • Implement it with TypeScript types (e.g. Record<number, { ... }>).
  • Add a function getTopCustomer() that returns the customerId with the highest total spending.

🧠 Evaluation Criteria

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

🧪 Expected Output

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment