1
1

More than 1 year has passed since last update.

JavaScript: reduce [アウトプット全くしてこなかったのでアウトプットする004]

Last updated at Posted at 2022-03-03

reduceを書くことがほぼなかったのでアウトプットします。

reduce() で一番わかりやすいのは、配列のすべての要素の和を返す場合でしょう。

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

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial);
// expected output: 10
(previousValue, currentValue) => previousValue + currentValue,

この第一引数のコールバック関数がreduceをわかりづらくしている所以だと個人的に思っています。
previousValueは今までの計算結果の「和」です。

適切な例えかわかりませんがバームクーヘンの作り方が浮かんだのでこれで説明します。

image.png

const initialValue = 0;

上記はバームクーヘンの一番内側です。

baumkuhen.png
baumkuhen.png

そして二番目にこの中で渡されるのが以下の部分。つまり生地を塗っていた今までの和です。

baumukuhen.jpeg
baumukuhen.jpeg

これをどんどん繰り返していき、最終的にsumWithInitialに渡されるのが以下のバームクーヘンです。

image.png

ちなみに以下のようにforEachでもできますが、初期値を処理の外で管理しないといけないため、どこかで値が書き変わってしまう可能性があり、危険ですし変数の存在を頭の中に入れないといけないので脳内メモリが奪われます。

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

let sum = 0;

array1.forEach((num) => {
  sum = sum + num;
});

console.log(sum); // 10

自分は今までこのようなコードを量産していたのですが、可読性、保守性が下がるのでreduceを使用するようにしていこうと思いました。

強くなりたい!!!!!!!

1
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
1
1