const orders = [
{
orderId: "ORD001",
customerId: "CUST1",
items: [
{ product: "Laptop", price: 1200, qty: 1 },
{ product: "Mouse", price: 25, qty: 2 },
],
status: "shipped",
timestamp: "2023-10-01T10:00:00Z",
},
{
orderId: "ORD002",
customerId: "CUST2",
items: [{ product: "Phone", price: 800, qty: 1 }],
status: "pending",
timestamp: "2023-10-02T15:30:00Z",
},
{
orderId: "ORD003",
customerId: "CUST1",
items: [
{ product: "Keyboard", price: 50, qty: 3 },
{ product: "Monitor", price: 300, qty: 1 },
],
status: "delivered",
timestamp: "2023-10-03T09:15:00Z",
},
];
const activeOrders = orders
.filter((order) => ["delivered", "shipped"].includes(order.status))
.map((order) => ({
...order,
totalAmount: order.items.reduce(
(sum, item) => sum + item.price * item.qty,
0
),
}));
console.log(activeOrders);
const result = activeOrders.reduce((acc, order) => {
const { customerId } = order;
if (!acc[customerId]) {
acc[customerId] = {
orders: [],
totalAmount: 0,
latestOrderDate: null,
};
}
// 최신 주문 날짜 비교
const currentLatest = acc[customerId].latestOrderDate
? new Date(acc[customerId].latestOrderDate)
: null;
const orderDate = new Date(order.timestamp);
if (!currentLatest || orderDate > currentLatest) {
acc[customerId].latestOrderDate = order.timestamp;
}
acc[customerId].orders.push(order);
acc[customerId].totalAmount += order.totalAmount;
return acc;
}, {});
console.log(result);