LoginSignup
314
249

More than 3 years have passed since last update.

【javascript】reduce

Last updated at Posted at 2016-09-06

reduceメソッドについてまとめます。

reduceメソッドとは

隣り合う2つの配列要素に対して左から右へ同時に関数を適用し、単一の値にする。というメソッドです。
例えば、「配列の中身を一つずつ足していって合計を求める」ということができます。

reduce()

以下、構文です。

array.reduce(callback [, initialValue])

  • array:対象となる配列
  • callback:配列内の各値に対して実行される関数、4つの引数を持つ
    • accumulator:現在処理されている要素よりも一つ前の要素かinitialValue、もしくは一つ前の要素で実行された関数の結果
    • currentValue:現在処理されている要素
    • currentIndex:現在処理されている要素のインデックス
    • array:対象となっている配列
  • initialValue:最初の実引数として渡される値

参考:Array​.prototype​.reduce()

initialValueは省略可能です。
initialValueが指定されている場合、一番最初の関数実行時のaccumulatorにはinitialValueの値が入り、currentValueには配列の最初の値が入ります。
initialValueが省略されている場合は、一番最初の関数実行時のaccumulatorには配列の最初の値が入り、currentValueには配列の2番目の値が入ります。

また、callback関数の中のcurrentIndex、arrayも省略可能です。

サンプルを通じて詳しく説明します。

サンプル

まずは配列内の数値をすべて足して、その値を表示します。

sample_sum.js
var array = [1, 2, 3];

var result = array.reduce(function (accumulator, currentValue, currentIndex, array) {
    return accumulator + currentValue;
});

console.log(result); // 6

sample_sum.jsではinitialValueを省略しています。
関数実行のイメージは以下のようになります。

関数実行回数 accumulator currentValue currentIndex
1回目 1 2 1
2回目 3 3 2

関数実行1回目のaccumulatorには配列の一番最初の要素である1が入ります。
currentValueには2が入ります。
ここで関数が実行されると、1 + 23がreturnされます。

関数実行2回目のaccumulatorには、一つ前の要素で実行された関数の結果である3が入ります。
currentValueには3番目の要素である3が入ります。
そして関数が実行された結果、6がreturnされます。

以下のように、配列の中で一番大きい値を求めることもできます。

sample_max.js
var array = [10, 100, 30, 50];

var result = array.reduce(function (accumulator, currentValue, currentIndex, array) {
    if(accumulator > currentValue){
        return accumulator;
    } else {
        return currentValue;
    }
});

console.log(result); // 100

以上でreduceの基本は終わりです。

314
249
3

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
314
249