In my React application, I have a table that fetches its data from an API.
I need to implement sorting for one of the columns. The values in this column are usually strings of numbers but sometimes can be equal to "-" (Dash).
Below is the sort function I am using:
if (order === "DEF") {
const sorted = props.currency.sort((a, b) =>
Number(a[obj1][obj2]) > Number(b[obj1][obj2])
? 1
: Number(b[obj1][obj2]) > Number(a[obj1][obj2]) || a[obj1][obj2] === "-"
? -1
: 0
);
props.setCurrency(sorted);
setOrder("ASC");
} else if (order === "ASC") {
const sorted = props.currency.sort((a, b) =>
Number(a[obj1][obj2]) < Number(b[obj1][obj2]) || a[obj1][obj2] === "-"
? 1
: Number(b[obj1][obj2]) < Number(a[obj1][obj2])
? -1
: 0
);
props.setCurrency(sorted);
setOrder("DSC");
} else {
const sorted = defaultCurrency;
props.setCurrency(sorted);
setOrder("DEF");
}
After applying the sort, I want to treat "-" as zero. However, when the order is ASC or DSC, items with "-" should always appear at the top of the table, while the other array items are sorted correctly.