Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Table not sorting numbers correctly

React-table is sorting decimals like this:

enter image description here

My guess is that, although I'm receiving numbers from server, react-table handles them as text. So, I modified the accessor like this:

accessor: d => Number(d.Invoice_Weight).toFixed(2)

but I keep getting the sorting wrong.

This is the code for column:

 {
                      Header: () => 
                      <DropDownMenu 
                      header={content[lang].Invoice_Weight}
                      openModal = {this.onOpenSelectColumnsModal}
                      />,
                      id: 'Invoice_Weight',
                      sortable: true,
                      accessor: d => Number(d.Invoice_Weight).toFixed(2),
                      //width: 200,
                      getProps: () => {
                        return {
                          style: {
                            textAlign: 'right'
                          }
                        }
                      },
                      show: Invoice_Weight,
                    },
like image 978
Morgana Avatar asked Jun 21 '19 14:06

Morgana


1 Answers

As suggested in other answers the issue is that toFixed returns a string and therefore the sorting will be done using string comparisons. However coercing back to number will not work in this case becase then you will lose trailing 0s which I'm guessing you still need.

Another solution is to use custom sorting:

accessor: d => Number(d.Invoice_Weight).toFixed(2),
sortMethod: (a, b) => Number(a)-Number(b)

You may want to refine sortMethod to handle NaNs and Infinities (if you have them) but that's the general idea

You can use this to coerce the string back to a number but only in the context of sorting without affecting the displayed value

like image 122
apokryfos Avatar answered Oct 18 '22 13:10

apokryfos