javascript エラー「Uncaught TypeError: The comparison function must be either a function or undefined」の解決方法

javascript エラー「Uncaught TypeError: The comparison function must be either a function or undefined」の解決方法

javascriptで、エラー「Uncaught TypeError: The comparison function must be either a function or undefined」が発生した場合の原因と解決方法を記述してます。

環境

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

エラー内容

以下のコードを実行時に発生。

const arr = [2,1,5,3,7]

const result = arr.sort(3)

console.log(result)

エラーメッセージ

Uncaught TypeError: The comparison function must be either a function or undefined
at Array.sort (<anonymous>

画像

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

Uncaught TypeError: invalid Array.prototype.sort argument

画像

原因

sort関数に指定できる引数は、値を比較できる関数である必要があるため

解決方法

sort関数に引数を使用する場合は、以下のようにします。下記は降順に並び替える場合のサンプルとなります。

const result = arr.sort((a, b) => (a < b ? 1 : -1));

実行結果