1
2

JavaScriptのreduce関数を理解する

Posted at

reduce関数とは

reduce関数は、配列の各要素に対して累積的な計算を行い、単一の値に畳み込む(=reduce)ための関数。つまり、配列全体を1つの値にまとめあげるための関数。

基本的な構文

array.reduce((accumulator, currentValue, currentIndex, array) => {
    //処理
}, initialValue);

各パラメータの意味

  • accumulator: 前回のreduceの実行結果が保持される値。初回はinitialValueが入る。
  • currentValue: 現在処理中の配列の要素。
  • currentIndex: 現在処理中の配列のインデックス。(省略可)
  • array: reduceが実行されている配列。(省略可)
  • initialValue: accumulatorの初期値。省略すると配列の最初の要素が使用され、currentValueは2番目の要素から始まる。

使用例

配列内の数値の合計を計算する

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
    return accumulator + currentValue;
}, 0);

console.log(sum);  // 15

配列のフラット化

const nestedArray = [[1, 2], [3, 4], [5, 6]];
const flatArray = nestedArray.reduce((accumulator, currentValue) => {
    return accumulator.concat(currentValue);
}, []);

console.log(flatArray);  // [1, 2, 3, 4, 5, 6]

値の出現回数をカウント

const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const fruitCount = fruits.reduce((accumulator, currentValue) => {
  if (accumulator[currentValue]) {
    accumulator[currentValue] += 1;
  } else {
    accumulator[currentValue] = 1;
  }
  return accumulator;
}, {});

console.log(fruitCount);  // { apple: 3, banana: 2, orange: 1 }

オブジェクトのグルーピング

const people = [
  { name: 'Alice', age: 21 },
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 21 },
  { name: 'David', age: 25 },
  { name: 'Eve', age: 30 }
];

const groupedByAge = people.reduce((accumulator, currentValue) => {
  const age = currentValue.age;
  if (!accumulator[age]) {
    accumulator[age] = [];
  }
  accumulator[age].push(currentValue);
  return accumulator;
}, {});

console.log(groupedByAge);
/*
{
  '21': [
    { name: 'Alice', age: 21 },
    { name: 'Charlie', age: 21 }
  ],
  '25': [
    { name: 'Bob', age: 25 },
    { name: 'David', age: 25 }
  ],
  '30': [
    { name: 'Eve', age: 30 }
  ]
}
*/

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