Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hot to properly sort mixed string/numbers data in proper order

Here is an object I want to sort by code field like: a1111, b1111, 22222:

const myObj = [{code: 'b1111'}, {code: '2222'}, {code: 'a1111'}]

and my sort function:

const sortData = (data) => {
    return data.sort((a, b) => {  
        return a.code < b.code ? -1 : a.code > b.code ? 1 : 0;
      });
  };

console.log(sortData(myObj))

I expect to get data sorted this way (any characters first then digits):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[ { code: 'a1111' }, { code: 'b1111' }, { code: '2222' } ]

but getting

[ { code: '2222' }, { code: 'a1111' }, { code: 'b1111' } ]

so how do I fix sort function?

>Solution :

You can split code by a regex and compare accordingly. If you want extended code page support, use Intl.Collator in the last comparison of the alpha chars.

const collator = Intl.Collator('en', {numeric:true});

const myObj = [{code: 'b1111'}, {code: '2222'}, {code: 'a1111'}];

const regex = /(\D*)(\d+)/;
myObj.sort(({code:a}, {code:b}) => {
  a = a.match(regex);
  b = b.match(regex);
  if(a[1] === b[1] || !a[1] && !b[1]) return +a[2] - +b[2];
  if(!a[1] && b[1]) return 1;
  if(!b[1] && a[1]) return -1;
  return a[1] > b[1] ? 1 : -1;
});

console.log(...myObj);
  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading