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):
[ { 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);