I have a table in my react app and it gets its data from API.
I want to sort one of its columns. a[obj1][obj2]
or b[obj1][obj2]
Usually is a string of numbers and sometimes are equal to "-"
(Dash)
this is my sort function:
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 the sort is called I want to behave with "-"
like a zero,
but the items which are equal to "-"
are always placed on the top of the table when the order is equal to ASC or DSC, while the other items of the array are sorted correctly.