Ant-design: Table sorting by text length or alphabetically?

Created on 20 May 2016  ·  10Comments  ·  Source: ant-design/ant-design

The table sorter is sorting text strings by length not alphabetically. I do not know how is this in Chinese language but in euro american countries sorting of text is done alphabetically.

Most helpful comment

It would be better to use JavaScript String#localeCompare function:

sorter: (a, b) => { return a.title.localeCompare(b.title)},

All 10 comments

[{
  title: 'age',
  dataIndex: 'age',
  sorter: (a, b) => a.age - b.age,
}]

You can specify your own sort algorithm. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

for sort by alpgavite:
function compareByAlph (a, b) { if (a > b) { return -1; } if (a < b) { return 1; } return 0; } ... sorter: (a, b) => compareByAlph(a.lastName, b.lastName),

It would be better to use JavaScript String#localeCompare function:

sorter: (a, b) => { return a.title.localeCompare(b.title)},

thx @Leong21 for this clever solution

I'm still unable to figure out how can we sort columns using Dates. I'm doing something like:

        sorter: (a, b) => {
          let dateA = !a.publishedAt
            ? new Date().getTime()
            : new Date(a.publishedAt).getTime();

          let dateB = !b.publishedAt
            ? new Date().getTime()
            : new Date(b.publishedAt).getTime();

          return [dateA, dateB].sort();
        }

But this isn't working. publishedAt can be either "" or some date like "21 May, 2017" or "21 May, 2017 3:05 PM".

@ghoshnirmalya try using moment.js if possible.

sorter: (a, b) => { return moment(a.publishedAt).unix() - moment(b.publishedAt).unix()}

in order to handle the situation where publishedAt == "" try:
sorter: (a, b) => { return moment(a.publishedAt || 0).unix() - moment(b.publishedAt || 0).unix() }

@Leong21 Thank you! That works as expected.

Good work @ leong21
actually The localeCompare() method compares two strings in the current locale.
and it would be better
sorter: (a, b) => { return a.title.localeCompare(b.title)},

@Leong21 Thank you! This should be explained or mentioned here:https://vue.ant.design/components/table/

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mineralres picture mineralres  ·  3Comments

AhmedSayed77 picture AhmedSayed77  ·  3Comments

Orbyt picture Orbyt  ·  3Comments

tianyacsdn picture tianyacsdn  ·  3Comments

drcmda picture drcmda  ·  3Comments