読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
予約の合計金額は、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円になります。
| 回 | item | sum の変化 |
|---|---|---|
| 1 | 食パン×1 | 0 → 380 |
| 2 | クロワッサン×2 | 380 → 820 |
!product は「product がない」という意味です。商品が見つからないときは、合計に何も足さずに次へ進みます。
products.filter((p) => p.price < 300)products.map((p) => `${p.name} ${p.price}円`)reduce を使う場合は、products にあんパン(p003)とメロンパン(p005)を加えたうえで、4.3 の書き方で計算します。17 / 18