読み方のヒント

矢印ボタン(または ← → キー)でページを移動できます。

第4節 配列とオブジェクト

4.3 reduce で合計する

予約の合計金額は、reduce で計算できます。

const items = [
  { productId: "p001", quantity: 1 },
  { productId: "p002", quantity: 2 },
];

const total = items.reduce((sum, item) => {
  const product = products.find((p) => p.id === item.productId);
  if (!product) {
    return sum;
  }
  return sum + product.price * item.quantity;
}, 0);
// 820

reduce は、配列の値を1つずつ使って、1つの値にまとめます。sum には途中までの合計が入り、最初の値は最後に書いた 0 です。この例は、予約 R-0001(食パン×1、クロワッサン×2)の合計で、380 + 220 × 2 = 820円になります。

回itemsum の変化
1食パン×10 → 380
2クロワッサン×2380 → 820

!product は「product がない」という意味です。商品が見つからないときは、合計に何も足さずに次へ進みます。

解答の例
  1. products.filter((p) => p.price < 300)
  2. products.map((p) => `${p.name} ${p.price}円`)
  3. 180 × 4 + 200 × 2 で 1,120円。reduce を使う場合は、products にあんパン(p003)とメロンパン(p005)を加えたうえで、4.3 の書き方で計算します。

17 / 18