LoginSignup
2
1

【JavaScript】reduceメソッドの使いかた

Posted at

はじめに

JavaScript Primerのサンプルコードに取り組んだ際、reduceメソッド部分の処理の流れが理解できず苦戦したので、簡単なサンプルを用いて整理しました。

reduceメソッドとは

配列に対して使えるメソッドです。

配列の各要素に対してコールバック関数を実行した結果を足し合わせていき、すべてを足した結果を返り値とします。

const totalValue = array.reduce(callback, [initialValue])

引数には以下を設定します。

  • callback:配列の各要素に対して呼び出されるコールバック関数
    • accumulator:合計値
    • currentValue:現在処理している要素の値
    • currentIndexcurrentValueの位置
    • array:reduceメソッドが呼び出された配列
  • initialValueaccumulatorの初期値。省略可能

では、具体例として、配列の合計値を求める処理を見ていきます。1

例1

[1, 2, 3, 4]という配列の要素を1つずつ足し合わせ、最終的な合計値を返しtotalValueに格納する処理です。

初期値として、initialValue(reduceメソッドの第二引数)に0を設定しています。

const array = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const totalValue = array.reduce((accumulator, currentValue) => {
    return accumulator + currentValue;
}, initialValue); // 初期値として0を設定

console.log(totalValue); // 10

コールバック関数の実行ごとの結果は以下のようになります。

accumulator currentValue return する値
1回目の呼び出し 0 (initialValue) 1 0 + 1 = 1
2回目の呼び出し 1 2 1 + 2 = 3
3回目の呼び出し 3 3 3 + 3 = 6
4回目の呼び出し 6 4 6 + 4 = 10

例2. initialValueを省略した場合

initialValue(reduceメソッドの第二引数)を省略すると、コールバック関数を最初に実行したとき、accumulatorには配列の最初の値が、currentValueには配列の2つ目の要素が格納されます。

const array = [1, 2, 3, 4];

// 1 + 2 + 3 + 4
const totalValue = array.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}); // 初期値を省略

console.log(totalValue); // 10

コールバック関数の実行ごとの結果は以下のようになります。

accumulator currentValue return する値
1回目の呼び出し 1 (array[0]の値) 2 (array[1]の値) 1 + 2 = 3
2回目の呼び出し 3 3 3 + 3 = 6
3回目の呼び出し 6 4 6 + 4 = 10

初期値を設定した場合より、呼び出し回数が1回減ることになります。

参考

  1. なお、今回の例ではコールバック関数の第三引数と第四引数は使用しないため指定しません。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1