Update: based on the feedback provided, the ordering sequence is as follows:
"" < "-inf" < "Nan" < "inf" < ... < -1 < 0 < 1 < ...
. To customize this, you can adjust the elements in the
order
array.
Keep in mind that if the array includes items not listed in the order
array, the code may not function correctly. To address this, consider implementing safeguards or including additional special elements (such as 0
) in the order
array.
It's important to note that in JavaScript, NaN
and Infinity
(not as string literals) are also considered numbers. This code ensures they are sorted alongside numerical values.
var basicCompare = function (a, b) {
if (a > b) return 1;
if (a < b) return -1;
return 0;
}
var compare = function (a, b) {
// 0 denotes numbers.
var order = ["", "-inf", "Nan", "inf", 0],
orderOfNumber = order.indexOf(0),
orderOfA = typeof(a) === "number" ? orderOfNumber : order.indexOf(a),
orderOfB = typeof(b) === "number" ? orderOfNumber : order.indexOf(b);
if (orderOfA === orderOfNumber && orderOfB === orderOfNumber) {
// Both are numbers, utilize standard comparison.
return basicCompare(a, b);
}
// If not both numbers, apply the predefined order.
return basicCompare(orderOfA, orderOfB)
}
array.sort(compare);