目的
redeuceについてわからなかったのでまとめてみる
reduce
配列のすべてのデータをまとめて1つの値に変換するための仕組み
配列名.reduce(コールバック関数(accumulator, currentValue,index), initialValue )
コールバック関数とは
現在の要素を処理する際に何をしたいかを記述する関数
reduceの中身の流れ
const numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((accumulator, currentValue,index) => {
console.log("accumulator",accumulator,"currentValue",currentValue,"index",index)
return accumulator + currentValue;
}, 0);
console.log("sum",sum);;
//accumulator 0 currentValue 1 index 0
//accumulator 1 currentValue 2 index 1
//accumulator 3 currentValue 3 index 2
//accumulator 6 currentValue 4 index 3
//accumulator 10 currentValue 5 index 4
//sum 15
-
accumulator
前回のCallback関数の結果が入る。
最初に呼ばれたときはInitialValueの初期値を使用
InitialValueの値がない場合は配列の一番最初の値が挿入される。 -
currentValue
現在の要素。今回は1, 2, 3, 4, 5が順番に処理される -
index
現在の要素の位置 -
initialValue
最初の実引数として渡される値
initialValueを設定した時の処理の流れ
const numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((accumulator, currentValue,index) => {
console.log("accumulator",accumulator,"currentValue",currentValue,"index",index)
return accumulator + currentValue
},3);
console.log("sum",sum);
//accumulator 3 currentValue 1 index 0
//accumulator 4 currentValue 2 index 1
//accumulator 6 currentValue 3 index 2
//accumulator 9 currentValue 4 index 3
//accumulator 13 currentValue 5 index 4
//sum 18
アロー関数 ES6以降で記載可能
const sum = [1, 2, 3, 4].reduce((accumulator,currentValue) =>
accumulator + currentValue);
returnを記載していないと、accumulatorとcurrentValueの推移が
わからないので注意
参考文献
https://note.com/nano_yoshizawa/n/nac237dcec66d
https://tech-blog.cloud-config.jp/2022-12-13-reduce-usage
https://qiita.com/chihiro/items/1047e40514a778c08baa