nikitha - 4 months ago 39

Javascript Question

I'm trying to sort an array that includes empty strings, numbers, "infinity", "-infinity", and "NaN". I am receiving all the values in form of strings, so sort is not working as expected when it comes to empty strings, inf and nan. Is there a way to customize my sort function both in ascending and descending order?

Answer

Edit: according to your comment, `"" < "-inf" < "Nan" < "inf" < ... < -1 < 0 < 1 < ...`

. You can change this by modifying the `order`

array.

Note this code will not work properly if the array contains elements that are not present in the `order`

array. You can either set guards for that, or add other special elements (like `0`

) to the `order`

array.

Also note `NaN`

and `Infinity`

(not a string literals) are also a number in javascript. Using this code, they will be ordered next to numbers.

```
var basicCompare = function (a, b) {
if (a > b) return 1;
if (a < b) return -1;
return 0;
}
var compare = function (a, b) {
// 0 represents 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) {
// They are both numbers, use regular comparison.
return basicCompare(a, b);
}
// They are not both numbers, so use the axiomatic order.
return basicCompare(orderOfA, orderOfB)
}
array.sort(compare);
```