LoginSignup
0
0

More than 1 year has passed since last update.

mapとreduceでforやif文を置き換える

Posted at

はじめに

最近、mapとreduceを用いた面白い配列操作を学んだので備忘録としてこちらにまとめます。

for文をmapで書き換える

配列内の値に変更を加えて再度配列に格納し直したい場合を考えてみます。

for文だと配列のlengthの数だけループを回して処理を加えたのち、新しく定義した配列にpushするという方法が考えられます。

forを使ったケース

const numArray = [1, 2, 3, 4, 5, 6];

const array = [];
for(let i = 0; i < numArray.length; i++){
  const doubleNum = numArray[i] * 2;
  array.push(doubleNum);
}

//出力 [2, 4, 6, 8, 10, 12]
console.log(array);

mapを使ったケース

これをmapで書くと以下のようにすっきりと書くことができます。

const numArray = [1, 2, 3, 4, 5, 6];

const array = numArray.map(el => el * 2);

//出力 [2, 4, 6, 8, 10, 12]
console.log(array);

reduceで配列内の数字の合計を出す

配列内の値を全て足し合わせたい場合。
forやmapで一つずつ取り出して足してもできますがreduceを使えば簡単です。

reduceで合計値を計算

const numArray = [1, 2, 2, 3, 3, 3, 3];

const getSum = array => {
  return numArray.reduce((a, b) => a + b, 0);
}

// 出力 17
console.log(getSum(numArray));

ループ処理とif文をreduceと三項演算子ですっきり書き換える

こちらは配列内に2以上の数字がいくつあるかを数える関数です。
for文とif文を組み合わせて算出することも可能ですが、これもreduceを使えばすっきり書けます。

forとif文のケース

const numArray = [1, 2, 3, 4, 5, 6];

const getCount = array => {
  let count = 0;
  array.forEach(num => {
    if(num > 2){
      count += 1;
    }
  });
  return count;
}

//出力 4
console.log(getCount(num));

reduceのケース

初期値を0に設定することで、三項演算子で記載した条件をクリアする値の数をカウントすることができています。


const count = numArray.reduce((a, b) => {
  return b > 2 ? a + 1 : a + 0;
}, 0);

//出力 4
console.log(count);

さいごに

mapもreduceもまだまだいろいろな使い方があります。
今後も新たな発見があればまとめていきたいと思います。

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