I'm dealing with an array of objects fetched from the backend. When mapping and sorting the data in ascending and descending order upon clicking a button, I encountered some issues with the onSort function. The problem lies in the handling of uppercase and lowercase characters, as well as numerical values and special characters like dollar signs.
For example:
$110, $12, $24000, $2500, $3
Instead of being sorted as:
$3, $12, $110, $2500, $24000
Or for a column with mixed case elements, it currently sorts like:
Apple, Banana, Dog, ant, candy
When it should ideally be:
ant, Apple, Banana, candy, Dog
The current logic also causes issues when sorting numbers like - 112,12,141,21,32,345,35;
However, it should display them as: 12,21,32,35,112,141,345;
Here is the snippet of code I have been using:
const [sort, setSort] = usestate("asc")
const onSort = (obj: string) => {
if (sort === "asc") {
const tableEl= [...tableItem].sort((a: any, b: any) => {
if (a[obj].split('/').reverse().join() > b[obj].split('/').reverse().join()) return 1;
else if (b[obj].split('/').reverse().join() > a[obj].split('/').reverse().join()) return -1;
else return 0;
});
setTableState({
...tstate,
tableItem: tableEl,
});
setSort("dsc")
}
if (sort === "dsc") {
const tableEl= [...tableItem].sort((a: any, b: any) => {
if (b[obj].split('/').reverse().join() > a[obj].split('/').reverse().join()) return
1;
else if (a[obj].split('/').reverse().join() > b[obj].split('/').reverse().join()) return -1;
});
setTableState({
...tstate,
tableItem: tableEl,
});
setSort("asc")
}
};