In this article we will show you the code to resolve TypeError: The comparison function must be either a function or undefined. It is raised if you provide wrong arguments to the javascript sort()
function. This function only accepts either undefined
or a function which can compare two variables.
Other forms of same error message are –
- TypeError: invalid Array.prototype.sort argument
- TypeError: Array.prototype.sort requires the comparator argument to be a function or undefined
Code Example –
TypeError –
[1, 3, 2].sort(5);
Correct –
[1, 3, 2].sort(); // [1, 2, 3]
TypeError –
const cmp = { asc: (x, y) => x >= y, dsc: (x, y) => x <= y }; [1, 3, 2].sort( cmp[this.key] || 'asc' );
Correct –
const cmp = { asc: (x, y) => x >= y, dsc: (x, y) => x <= y }; [1, 3, 2].sort( cmp[this.key || 'asc'] ); // [1, 2, 3]
Source – MDN