Home > other >  How can I order a table with decimal numbers and letters
How can I order a table with decimal numbers and letters

Time:10-18

Hello I'm facing a problem.

I want to order my table by decimal and after by letter.

For exemple I got this :

5.3 Choice 3
A-Choice 4
1.2 Choice 1
1.5 Choice 2
C-Choice 5

And I want it to be that way :

1.2 Choice 1
1.5 Choice 2
5.3 Choice 3
A-Choice 4
C-Choice 5

I tried something like that

const compare = (a, b) => {
        if (!isNaN(b.label.charAt(0)))
        {
            if (a.label === b.label) {
                return 0
             };
             const aArr = a.label.split("."), bArr = b.label.split(".");
             for (let i = 0; i < Math.min(aArr.length, bArr.length); i  ) {
                if (parseInt(aArr[i]) < parseInt(bArr[i])) {
                   return -1
                };
                if (parseInt(aArr[i]) > parseInt(bArr[i])) {
                   return 1
                };
             }
             if (aArr.length < bArr.length) {
                return -1
             };
             if (aArr.length > bArr.length) {
                return 1
             };
             return 0;
        }
        else
        {
            return a.label > b.label;
        }
        
     };
     processus.sort(compare);

But it's not working.. Thanks.

CodePudding user response:

Try the sort using string comparison (i.c. localeCompare)

const initial = `5.3 Choice 3
A-Choice 4
1.2 Choice 1
1.5 Choice 2
C-Choice 5`;

console.log(
  initial.split(`\n`)
    .sort( ( a, b ) => a.localeCompare(b))
    .join(`\n`)
);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

This can easily be achieved with localeCompare.

const arr = [
  '5.3 Choice 3',
  'A-Choice 4',
  '1.2 Choice 1',
  '1.5 Choice 2',
  'C-Choice 5',
];

const result = arr.sort((a, b) => a.localeCompare(b));

console.log(result);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related