test
test

Reputation: 2466

React Material UI Table Name Sorting seems little bit off

Quick question about sorting the table. Anyone can explain why it's not sorting ASC or DESC example taken straight from Material UI Example: https://codesandbox.io/s/13r5l3qyz3,

Results:

Gargantua
Koala Den
aorro

or

aorro
Koala Den
Gargantua

Thanks

Upvotes: 2

Views: 5821

Answers (2)

seema wadhwani
seema wadhwani

Reputation: 11

Converting the data to lower/upper case while comparing helps solve the problem. This also works for strings starting with numbers. (i.e. for an array like ['Aeon', '3F Works', 'mBand', 'MAQ'] Here is the sample code:

  const data =
      order === "desc"
        ? this.state.data.sort((a, b) => (b[orderBy].toLowerCase() < a[orderBy].toLowerCase() ? -1 : 1))
        : this.state.data.sort((a, b) => (a[orderBy].toLowerCase() < b[orderBy].toLowerCase() ? -1 : 1));

Upvotes: 1

Jules Dupont
Jules Dupont

Reputation: 7567

This behavior comes from the way the sort is implemented in this example. Here's the sort function (line 215 in the CodeSandbox you linked to):

const data =
  order === "desc"
    ? this.state.data.sort((a, b) => (b[orderBy] < a[orderBy] ? -1 : 1))
    : this.state.data.sort((a, b) => (a[orderBy] < b[orderBy] ? -1 : 1));

Assuming that you're ordering by name and order === "desc", that'll basically boil down to:

const data = this.state.data.sort((a, b) => (b.name < a.name ? -1 : 1));

So, the final order will be a result of comparisons that look like this:

"Koala Den" < "aorro"
"Gargantua" < "Koala Den"

But, JavaScript string comparison can have surprising results. Specifically, since the K in "Koala Den" is uppercase and the a in "aorro" is lowercase, this will be the result:

"Koala Den" < "aorro" // true
"Gargantua" < "Koala Den" // true

So, the sort is working as expected given the sorting method used. It's just not a case-insensitive string sort like you might expect.

You can check this by making "aorro" start with an uppercase A. Then the sort will have the expected results.

To fix this problem, the sort function would probably have to be re-implemented to work with all of the types that could be present in each column.

Upvotes: 2

Related Questions