JavaScript sort method requires a function as a parameter that can compare two elements of the array and return either a positive number, or a negative number or zero. Number is the keyword here.
BigInt operations like addition and subtraction returns BigInt type and not a Number type. And that's why the error you are getting.
So, Something like this should do the job
const big = [1n, 2n, 3n, 4n];
big.sort((a ,b) => {
if(a > b) {
return 1;
} else if (a < b){
return -1;
} else {
return 0;
}
});
console.log(big);
Interestingly, MDN document that I linked to previously, also suggests how to sort an array of BigInts, and it is concise:
Copying the whole section here for posterity:
const mixed = [4n, 6, -12n, 10, 4, 0, 0n]
// ↪ [4n, 6, -12n, 10, 4, 0, 0n]
mixed.sort() // default sorting behavior
// ↪ [ -12n, 0, 0n, 10, 4n, 4, 6 ]
mixed.sort((a, b) => a - b)
// won't work since subtraction will not work with mixed types
// TypeError: can't convert BigInt to number
// sort with an appropriate numeric comparator
mixed.sort((a, b) => (a < b) ? -1 : ((a > b) ? 1 : 0))
// ↪ [ -12n, 0, 0n, 4n, 4, 6, 10 ]