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?

More than 1 year has passed since last update.

【メモ】reduceとは?

0
Posted at

基本構文

array.reduce((累積値, 現在の要素, 現在のインデックス, 配列全体) => {
  // 処理内容
}, 初期値);
  • 累積値(acc とか total と書かれる)→ 前回の結果(蓄積された値)
  • 現在の要素(cur)→ 今処理している要素
  • 初期値 → reduce の最初の 累積値 として使われる

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

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

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

console.log(sum); // 10

acc は最初は 0。
 → 1回目:0 + 1 → 1
 → 2回目:1 + 2 → 3
 → 3回目:3 + 3 → 6
 → 4回目:6 + 4 → 10

例②:オブジェクトの配列から合計を取る

const items = [
 { name: "apple", price: 120 },
 { name: "banana", price: 80 },
 { name: "orange", price: 100 }
];

const totalPrice = items.reduce((acc, item) => acc + item.price, 0);

console.log(totalPrice); // 300

例③:配列から頻度表を作る

const fruits = ["apple", "banana", "apple", "orange", "banana", "apple"];

const count = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});

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

acc をオブジェクトとして使って、各フルーツの出現回数をカウントしている

reduce を使うべき場面
  • 合計値や平均を出したいとき
  • 配列からオブジェクトを作りたいとき
  • 配列を加工して別の形に変換したいとき(カスタムな集計)
わかりやすくするコツ
  • 最初は for や forEach で同じ処理をしてみてから reduce に書き換えると理解が早い
  • 初期値をしっかり決める(配列やオブジェクトでもOK)
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?