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 3 years have passed since last update.

【詰まったログ】JS reduce( )でエラー

Last updated at Posted at 2021-09-09

#やりたいこと
各配列の数値をそれぞれ合計したい

data:[
	   []
	   [300000, 600000]
	   []
	   [100007, 99999]
]

#エラー内容
下記でConsole.log(total)するとエラーになる

let total = data.map((val) =>
    val.reduce((sum, i) => sum + i)
  );

#原因
初期値(initialValue)を設定していなかったので、配列がカラ(合計するものがない)ときにエラーが出たようです。
参照:Array.prototype.reduce()

オブジェクトの配列に含まれた値の合計値を出すには、すべての項目を関数内で取得できるようにするために initialValue を指定する必要があります。

#解決策

let total = beneficiariesData.map((val) =>
    val.reduce((sum, i) => sum + i, 0)
  );

結果

	   []
	   [900000]
	   []
	   [110,006]

末尾に初期値として0を設定すると合計できました

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?