reduce() メソッド
累積値(アキュムレータ)と配列の要素を順番にコールバック関数へ渡し、1つの累積値を返します。 配列から配列以外を含む任意の値を作成したい場合に利用します。
つまり、配列を使って何かひとつの値を作成する。
内容
引数
第一引数にはコールバック関数に累積値, 要素, インデックス, 配列を引数として渡します。
第二引数には累積値の初期値となる値を渡せます。
- それぞれの引数について
・accumulator(累積値) 現在処理されている要素よりも一つ前の要素かinitialValue、もしくは一つ前の要素で実行された関数の結果 ・currentValue(要素) 現在処理されている要素 ・index(インデックス) 現在処理されている要素のインデックス ・array(配列) 対象となっている配列 ・initialValue(累積値の初期値) 最初の実引数として渡される値
実際のコード
配列の全要素の加算
const array = [1, 2, 3] const totalValue = array.reduce((accumulator, currentValue, index, array) => { return accumulator + currentValue }, 0) // 0がinitialValue console.log(totalValue)// => 6
- それぞれの引数はどのようになっているか
callback の反復 | accumulator | currentValue | currentIndex | array | 返値 |
---|---|---|---|---|---|
初回の呼出し | 0 | 1 | 0 | [1, 2, 3] | 1 |
2 回目の呼出し | 1 | 2 | 1 | [1, 2, 3] | 3 |
3 回目の呼出し | 3 | 3 | 2 | [1, 2, 3] | 6 |
- 初回の呼び出し
- accumulatorの0は、initialValueの0
- currentValueは配列の先頭の1
- 配列の先頭のインデックスは0
- arrayはそのまま
- 返値は0+1なので1
- 2回目の呼び出し
- accumulatorに前回の返値の1が入る
あとは同じように繰り返していく
引数の省略
「インデックス, 配列」、「累積値の初期値」の引数は省略可
上コードの引数省略版、プロセスは異なる
const array = [1, 2, 3] const totalValue = array.reduce((accumulator, currentValue) => { return accumulator + currentValue }) console.log(totalValue) // => 6
initialvalueが省略されたので、
accumulatorには配列の最初の要素1が入り、
currentValueにはその次の要素2が入る
callback の反復 | accumulator | currentValue | currentIndex | array | 返値 |
---|---|---|---|---|---|
初回の呼出し | 1 | 2 | 1 | [1, 2, 3] | 3 |
2 回目の呼出し | 3 | 3 | 2 | [1, 2, 3] | 6 |
引数を省略してはいけないときもある
配列内のオブジェクトのバリューの合計を取得
const sum = [{x: 1}, {x: 2}, {x: 3}].reduce((accumulator, currentValue) => { return accumulator + currentValue.x }, 0) console.log(sum) // => 6
initialValueを指定しないといけない
initialValueないと [object Object]23
と予期しない結果になる
他には
配列の最大の要素を取得する
const array = [5, 10, 100, 30, 500, 200] const result = array.reduce((accumulator, currentValue) => { if (accumulator > currentValue) { return accumulator } else { return currentValue } }) console.log(result) // => 500
どのように処理されているか確認する
console.log
で何がreturn
され、次の呼び出しでaccumulatorに入るかわかる
const array = [5, 10, 100, 30, 500, 200] const result = array.reduce((accumulator, currentValue) => { if (accumulator > currentValue) { console.log(accumulator) return accumulator } else { console.log(currentValue) return currentValue } }) console.log(result) /* => 10 100 100 500 500 500 */