JavaScript | 配列メソッドの使い分け(map / forEach / filter / reduce の違い)

JavaScript JavaScript
スポンサーリンク

では「税込み金額と商品点数も含めたカート概要」を作ってみましょう。


カートの例

const cart = [
  { name: 'Tシャツ', price: 1500, quantity: 2 },
  { name: 'ジーンズ', price: 5000, quantity: 1 },
  { name: '帽子', price: 2000, quantity: 1 },
  { name: '靴', price: 8000, quantity: 1 },
  { name: 'バッグ', price: 6000, quantity: 1 }
];
JavaScript

リスト要約関数(再利用)

function summarizeList(items, max = 3) {
  if (items.length === 0) return '商品はありません';

  if (items.length <= max) {
    return items.join(', ');
  } else {
    const shown = items.slice(0, max).join(', ');
    const remaining = items.length - max;
    return `${shown} …他${remaining}件`;
  }
}
JavaScript

カート概要を作る関数

function cartSummary(cart, taxRate = 0.1) {
  // 数量がある商品だけ残す
  const validItems = cart.filter(item => item.quantity > 0);

  // 商品名リスト
  const names = validItems.map(item => item.name);
  const nameList = summarizeList(names);

  // 合計金額(税抜)
  const subtotal = validItems
    .map(item => item.price * item.quantity)
    .reduce((acc, subtotal) => acc + subtotal, 0);

  // 税込み金額
  const totalWithTax = Math.floor(subtotal * (1 + taxRate));

  // 商品点数
  const itemCount = validItems.reduce((acc, item) => acc + item.quantity, 0);

  return `カート: ${nameList} / ${itemCount}点 / 合計: ${subtotal.toLocaleString()}円 (税込 ${totalWithTax.toLocaleString()}円)`;
}

// 実行
console.log(cartSummary(cart));
// "カート: Tシャツ, ジーンズ, 帽子 …他2件 / 5点 / 合計: 17,000円 (税込 18,700円)"
JavaScript

ポイント

  • 税率は引数で変更可能(デフォルト10%)
  • toLocaleString() で金額を「3桁区切り」にフォーマット
  • 点数は数量の合計で計算

💡 これで「UIにそのまま表示できるカート概要」が完成しました。
実務ではこの文字列を ショッピングサイトのヘッダー注文確認画面に出すと便利です。

タイトルとURLをコピーしました