【JavaScript】配列を1つの値にまとめる!reduce() メソッドの使い方
JavaScriptの配列メソッドの中でも、少し複雑で敬遠されがちなのが reduce() メソッドです。 map や filter はよく使うけれど、reduce はイマイチ仕様がわからなくて for 文で済ませてしまう…という方も多いのではないでしょうか?
reduce() の最大の特徴は、「配列の複数のデータを、最終的に1つの値にまとめる(集計する)」ことです。 今回は「ショッピングカート内の合計金額の計算」を例に、reduce() の仕組みと便利さを分かりやすく解説します!
デモ動作
See the Pen JSのreduce()メソッドで配列を集計! by mikanbako (@mikanbako) on CodePen.
demo: reduce()メソッドで配列を集計
実装コード紹介
【HTML】
<div class="l-wrap">
<h2>reduce() で合計金額を計算</h2>
<p class="p-desc">ボタンを押すと、カート内の商品の合計金額を集計して表示します!</p>
<div class="p-demo-box">
<!-- カートの中身リスト -->
<ul class="c-cart-list js-cart-list">
<!-- JSでリストを生成します -->
</ul>
<!-- 計算ボタン -->
<button class="c-btn js-calc-btn">合計金額を計算する</button>
<!-- 結果表示エリア -->
<div class="p-result">
<p class="c-text-label">合計金額:</p>
<div class="c-result-box"><span class="js-total-price">0</span> 円</div>
</div>
</div>
</div>
【CSS】
/* ベース装飾 */
.l-wrap {
padding: 40px 20px;
max-width: 500px;
margin: 0 auto;
color: #3e3e3e;
text-align: center;
}
h2 {
margin-bottom: 10px;
font-size: 16px;
color: #1bb4d4;
}
.p-desc {
margin-bottom: 30px;
font-size: 16px;
font-weight: bold;
color: #666;
line-height: 1.6;
}
.p-demo-box {
padding: 30px;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 15px rgb(0 0 0 / 5%);
}
/* カートリスト */
.c-cart-list {
padding: 0;
margin-bottom: 20px;
text-align: left;
list-style: none;
}
.c-cart-list li {
display: flex;
justify-content: space-between;
padding: 12px 20px;
margin-bottom: 10px;
font-size: 16px;
font-weight: bold;
background: #e0f7fa;
border: 2px dashed #1bb4d4;
border-radius: 6px;
}
/* ボタンと結果 */
.c-btn {
width: 100%;
padding: 12px 24px;
margin-bottom: 20px;
font-size: 18px;
font-weight: bold;
color: #fff;
cursor: pointer;
background: #e83e8c;
border: none;
border-radius: 8px;
transition: 0.3s;
}
.c-btn:hover {
opacity: 0.8;
transform: translateY(-2px);
}
.p-result {
padding-top: 20px;
text-align: left;
border-top: 2px solid #eee;
}
.c-text-label {
margin-bottom: 5px;
font-size: 14px;
color: #999;
}
.c-result-box {
font-size: 28px;
font-weight: bold;
color: #e83e8c;
text-align: right;
}
【JavaScript】
// 💡 カートに入っている商品のデータ
const cartItems = [
{ name: "🍎 りんご", price: 150 },
{ name: "🍌 ばなな", price: 200 },
{ name: "🍇 ぶどう", price: 400 },
{ name: "🍉 スイカ", price: 1000 }
];
// DOMの取得
const listContainer = document.querySelector('.js-cart-list');
const calcBtn = document.querySelector('.js-calc-btn');
const totalDisplay = document.querySelector('.js-total-price');
// 画面にリストを表示する処理
cartItems.forEach(item => {
const li = document.createElement('li');
li.innerHTML = `<span>${item.name}</span> <span>${item.price}円</span>`;
listContainer.appendChild(li);
});
// 💡 計算ボタンを押した時の処理
calcBtn.addEventListener('click', () => {
// reduceで合計金額を一気に計算!
const totalPrice = cartItems.reduce((accumulator, currentItem) => {
return accumulator + currentItem.price;
}, 0); // この「0」は初期値(最初は0円からスタート)
// 画面に表示
totalDisplay.innerText = totalPrice.toLocaleString(); // カンマ区切りで見やすく
});
コードの解説と仕組み
reduce() の引数は「箱」と「今見ている要素」
reduce のコールバック関数には、主に2つの引数が入ります。
accumulator(累積値):足し算の結果をずっと貯めておく「箱」のようなものです。currentItem(現在の値):配列の中から今順番に取り出している要素(りんご、ばなな…)です。
最後の 0 は何?(初期値の重要性)
// reduceで合計金額を一気に計算!
const totalPrice = cartItems.reduce((accumulator, currentItem) => {
return accumulator + currentItem.price;
}, 0); // この「0」は初期値(最初は0円からスタート)
メソッドの最後にある }, 0); の 0 は、「箱(accumulator)の最初の状態」を指しています。 つまり、「最初は合計0円からスタートして、そこに現在のアイテムの価格(currentItem.price)をどんどん足し算していってね!」という命令になっています。
これをもし for 文で書こうとすると、外側に let total = 0; のような変数を事前に用意しなければなりませんが、reduce なら事前の変数宣言なしで1つの変数(const totalPrice)で計算ができます!
補足:公式ドキュメント
まとめ
今回はJavaScriptの reduce() メソッドについて、ショッピングカートの合計金額の計算を例に解説しました。
一見すると引数が多くて難しそうに感じるメソッドですが、「アキュムレータ」と「初期値」の役割さえ理解してしまえば、for文を使うよりもはるかに短く、美しくデータを集計することができます。
今回のような数値の合計だけでなく、配列データのグループ化など、複雑なデータ処理をシンプルに記述したい場面で大活躍するメソッドなので、ぜひ積極的に使ってみてくださいね!