Array.reduce

mozillaには下記のように説明されている。

reduce() メソッドは、配列の各要素に対して (引数で与えられた) reducer 関数を実行して、単一の結果値にします。

配列に対して値(number,string,Objectなど)を返す。

型宣言

reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T): T;
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T, initialValue: T): T;
reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U, initialValue: U): U;
1
2
3

parameterの説明

  • previousValue
    • 最終的に返さえる値(string,number,Objectなど)、返す同じ箱のようなもの。初期値はinitialValueで定義する
  • currentValue
    • 現在処理されている配列の要素
  • currentIndex
    • 現在処理されている配列のインデックス(0,1,2,3,.....)
  • array
    • reduce()が呼び出された配列
  • initialValue
    • 初期値

使い方例

色々できる。

  • 数値の配列の合計値を返す。
  • 文字の配列の結合した値を返す。
  • オブジェクトの配列の一部の合計値を返す。
  • オブジェクトの配列の複数部を利用した計算値を返す。

数値の配列の合計値を返す

const amount = [1, 2, 3, 4];
const sum = amount.reduce((previousValue, currentValue) => previousValue + currentValue, 0)
console.log(sum); // 10
1
2
3
4
5

文字の配列の結合した値を返す

const amount = ['1', '2', '3', '4'];
const sum = amount.reduce((previousValue, currentValue) => previousValue + currentValue, '')
console.log(sum); // '1234'
1
2
3
4
5

オブジェクトの配列の一部の合計値を返す

肉の合計gramグラムを返す。

interface IMeat {
    name: string,  // 名前
    gram: number,  // グラム
    per100g: number  // 100グラム当りの価格
}
const meat: IMeat[] = [
    { name: '鶏肉', gram: 150, per100g: 80 },
    { name: '牛肉', gram: 500, per100g: 200 },
    { name: '豚肉', gram: 400, per100g: 150 },
];
const sumGram = meat.reduce((previousValue, currentValue) => previousValue + currentValue.gram, 0);
console.log(sumGram);  // 1050
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

オブジェクトの配列の複数部を利用した計算値を返す

gram / 100 * per100gの合計値である、肉の合計金額を返す。

interface IMeat {
    name: string,  // 名前
    gram: number,  // グラム
    per100g: number  // 100グラム当りの価格
}
const meat: IMeat[] = [
    { name: '鶏肉', gram: 150, per100g: 80 },
    { name: '牛肉', gram: 500, per100g: 200 },
    { name: '豚肉', gram: 400, per100g: 150 },
];
const price = meat.reduce((previousValue, currentValue) =>
    previousValue + (currentValue.gram / 100 * currentValue.per100g)
    , 0);
console.log(price);  // 1720
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17