1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】reduce関数の挙動を理解する

Posted at

reduceとは

reduce関数は、配列の要素を順番に処理して、最終的に1つの値にまとめるメソッドです。配列を「縮小」するイメージで、合計値の計算や配列の変換など、様々な場面で活躍します。

基本的な構文

配列.reduce((累積値, 現在の値, インデックス, 元の配列) => {
  // 処理
  return 新しい累積値;
}, 初期値);

必須のパラメータは最初の2つだけです。

  • 累積値: 前回の処理結果を保持する値
  • 現在の値: 今処理している配列の要素
  • 初期値: 累積値の初期値(省略可能ですが、指定を推奨)

動作の流れ

reduceがどのように動くのか、図で見てみましょう。

具体例で確認します。

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

console.log(sum); // 10

このコードの実行過程は以下の通りです。

実用的な使用例

配列の合計値を計算

const prices = [100, 200, 300];
const total = prices.reduce((sum, price) => sum + price, 0);
// 結果: 600

配列から特定の形式に変換

商品リストから、カテゴリごとにグループ化する例です。

const products = [
  { name: 'りんご', category: '果物' },
  { name: 'にんじん', category: '野菜' },
  { name: 'バナナ', category: '果物' }
];

const grouped = products.reduce((acc, product) => {
  const category = product.category;
  if (!acc[category]) {
    acc[category] = [];
  }
  acc[category].push(product.name);
  return acc;
}, {});

// 結果: { 果物: ['りんご', 'バナナ'], 野菜: ['にんじん'] }

配列の最大値を見つける

const numbers = [5, 2, 8, 1, 9];
const max = numbers.reduce((max, current) => {
  return current > max ? current : max;
});
// 結果: 9

初期値を省略した場合の挙動

初期値を省略すると、配列の最初の要素が初期値となり、2番目の要素から処理が始まります。

const numbers = [1, 2, 3, 4];

// 初期値あり
const sum1 = numbers.reduce((acc, current) => acc + current, 0);
// 処理回数: 4回(0+1, 1+2, 3+3, 6+4)

// 初期値なし
const sum2 = numbers.reduce((acc, current) => acc + current);
// 処理回数: 3回(1+2, 3+3, 6+4)

ただし、空配列に対して初期値なしでreduceを実行するとエラーになるため、初期値の指定を推奨します。

まとめ

reduceは配列を1つの値にまとめる強力なメソッドです。最初は難しく感じるかもしれませんが、「累積値を更新しながら配列を処理する」という基本を押さえれば、様々な場面で活用できますね。

処理の流れを図で理解し、簡単な例から試してみることをお勧めします。​​​​​​​​​​​​​​​​

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?