grid-js / gridjs

Advanced table plugin
https://gridjs.io
MIT License
4.38k stars 241 forks source link

Sorting problem on numbers when using the from option #1461

Open barberob opened 2 months ago

barberob commented 2 months ago

Describe the bug The sorting is wrong on numbers when creating from an html table.

To Reproduce Steps to reproduce the behavior:

  1. create an html table, with a column id and a incremental number on each row : 1, 2, 3, 4, .... and create a new Grid() from that table
  2. Click on sort on that column
  3. you will have it sorted like a string : 1, 10, 100, 101, 102 103, ...

Expected behavior This should sort it like a number 1, 2, 3, 4 becomes 4, 3, 2, 1

Screenshots image image

Desktop / Smartphone not os specific

matzeeable commented 2 months ago

Running into the same issue. I searched the coding of Gridjs and looked for a way to set a custom sorter for a from-table generated table like documented in https://gridjs.io/docs/config/sort#column-specific-sort-config, but did not found a solution for this. Is there a way to configure column specific sorting when using from?

becurrie commented 1 month ago

Would like an answer on this one if possible 👍

kopepasah commented 1 month ago

@barberob @matzeeable it sounds like you are trying to perform a numeric comparison without using a custom comparator function. In JavaScript array.sort() converts the elements of the array to strings and then compares their sequences of UTF-16 code unit values (lexicographical, not numerical). In order to achieve the desired result, you must use a custom comparator function to achieve numeric sorting.

@afshinm one thing you could probably change is to first check if the values being sorted are numeric, but that will likely come with its own challenges, especially considering there is already a way to achieve numeric sorting with a custom comparator function.