0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ES6で追加されたループ処理メソッドをまとめる【reduce】

Last updated at Posted at 2021-01-31

reduceはどういうメソッドか?

reduceが、その他のループ処理メソッドと大きく異るのは、累積値を持てるところです。
その特性から、配列の要素を累積していき、1つの値にするする際に最適なメソッドです!

簡単な例だとこんな感じです↓

//numbers配列の中身を合計していく処理

const numbers = [1,2,3,4,5];
let result = numbers.reduce(function(acc, num) {
 
  return acc + num;
 
},0)
 
console.log(result);

// 15 が出力されます

構文

それではreduceの構文と挙動について見ていきます。

// 上と同じサンプルです。
const numbers = [1,2,3,4,5];

let result = numbers.reduce(function(acc, num) {
//reduce()の中でコールバック関数を書きます
//コールバック関数の引数には、(累積値,配列の各要素)を取ります

  return acc + num;
// 実行したい式

},0)
// 初期値(acc)の値をセット

この例だと、accは0から始まりループが終わるごとに returnされた結果がセットされていくことになります。
そしてaccは次回の処理に引き継がれていきます。

実行回数 acc
1回目 1
2回目 3
3回目 6

いろんなサンプル

配列が持つ要素の文字列合計を集約
const animals = ["cat","dog","fish"];

let total = animals.reduce(function(acc, word) {
  return acc + word.length;
}, 0);
累積値を配列にしてmapのような動きをさせる
const primaryColors = [
  {color:"red"},
  {color:"yellow"},
  {color:"blue"}
];

primaryColors.reduce(function(acc, pc) {
  acc.push(pc.color);
  return acc
}, []);
プロパティを集約してみる
const desks = [
  { type: 'sitting' },
  { type: 'standing' },
  { type: 'sitting' },
  { type: 'sitting' },
  { type: 'standing' }
];

let deskTypes = desks.reduce(function(acc, el) {
    if(el.type === "sitting"){
        acc.sitting +=1;
    }else{
        acc.standing +=1;
    }
    
    return acc;
}, { sitting: 0, standing: 0 });
0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?