JavaScript 데이터02

문제 1: 주문 데이터 필터링 및 총액 계산 (중급)

  • 배송된(delivered) 또는 발송된(shipped) 주문만 필터링하세요.
  • 각 주문의 총 주문 금액(totalAmount)을 계산하여 추가하세요.
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);

설명

  1. filter()를 사용해 상태가 delivered 또는 shipped인 주문만 남깁니다.
  2. map()을 이용해 각 주문에 새로운 속성 totalAmount를 추가합니다.
  3. reduce()를 활용해 items 배열 내 제품 가격과 수량을 곱한 후 합산합니다.

문제 2: 고객별 주문 요약 (고급)

  • 각 고객(customerId)별로 주문 내역을 그룹화하세요.
  • 각 고객의 총 주문 금액을 계산하세요.
  • 최신 주문 날짜를 추적하세요.
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);

설명

  1. reduce()를 이용해 고객 ID(customerId)를 키로 하는 객체를 생성합니다.
  2. if (!acc[customerId])를 통해 해당 고객 ID가 처음 등장하는 경우 기본 구조를 초기화합니다.
  3. 주문별 총 금액을 누적(totalAmount)하여 관리합니다.
  4. latestOrderDate를 갱신할 때, timestamp 문자열을 Date 객체로 변환 후 비교합니다.
    • new Date(order.timestamp)을 사용하면 ISO 8601 문자열을 Date 객체로 변환할 수 있습니다.
    • 날짜 비교 시 orderDate > currentLatest를 이용하면 최신 날짜를 업데이트할 수 있습니다.
    • Date 객체끼리 비교할 때는 내부적으로 getTime() 값(밀리초 단위 숫자)을 비교하므로 date1 > date2처럼 직접 비교 가능합니다.