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

配列の要素を1つの値に「集約」する処理:reduce

Posted at

reduceは配列の要素を1つの値に集約する

reduceはJavaScriptの配列メソッドの一つで、配列の要素を1つに集約することができる。

reduceの基本構文

array.reduce((累積値, 現在の値) => {
  return 新しい累積値;
}, 初期値);

例1:配列の合計を求める

例えば、配列の数値の合計などを求めたいとき

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

const sum = numbers.reduce((acc, curr) => {
  return acc + curr;
}, 0);

console.log(sum); // 15

例2:オブジェクトの合計(家計簿アプリなど)

オブジェクト内の数値に関しても同様に使用可能

const transactions = [
  { type: 'income', amount: 1000 },
  { type: 'expense', amount: 500 },
  { type: 'income', amount: 2000 },
];

const totalIncome = transactions
  .filter(t => t.type === 'income')
  .reduce((acc, t) => acc + t.amount, 0);

console.log(totalIncome); // 👉 3000

役立つ場面

値を集約するのに活用できるため、家計簿アプリ、会計アプリなど数値を多く扱うものに向いていそうです。

最後に

reduceなど数値を扱うためのメソッドは数多くあるので、それぞれ役割を理解して使用する場面を考えてく必要があります。

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