javascript エラー「Uncaught TypeError: Reduce of empty array with no initial value」の解決方法

javascript エラー「Uncaught TypeError: Reduce of empty array with no initial value」の解決方法

javascriptで、エラー「Uncaught TypeError: Reduce of empty array with no initial value」が発生した場合の原因と解決方法を記述してます。空の配列に対して「reduce」を実行した際に発生します。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 107.0.5304.88

エラー内容

以下のコードで発生。

let arr = [0, 1, 2]

arr.filter(x => x > 2).reduce((x, y) => x + y)

エラーメッセージ

Uncaught TypeError: Reduce of empty array with no initial value
    at Array.reduce (<anonymous>)

画像

firefox(バージョン106)では、以下のエラーとなります。

Uncaught TypeError: reduce of empty array with no initial value

画像

原因

「filter」使用時に、条件にあう値が存在しないため、空の配列に「reduce」を実行してるのでエラーとなります。

解決方法

「filter」の結果が空でない場合のみ、実行する

let arr = [0, 1, 2]
let result = arr.filter(x => x > 2)

if ( result.length ) {
  let sum = result.reduce( (x, y) => x + y )
  console.log(sum)
}

「filter」の条件を変更すると「reduce」が実行されます。

let arr = [0, 1, 2]
let result = arr.filter(x => x > 0)

if ( result.length ) {
  let sum = result.reduce( (x, y) => x + y )
  console.log(sum)
}

実行結果