Need some help in sorting time zone. here is my code:
I would like to sort by -
then nutral
(no - or ) then
. at present it sorts at -
,
andnutral
.
sorting code:
const SortTimezoneCompare = (data) => {
return data.sort((a, b) => {
var re = /^\(GMT([ -]\d{1,2}):(\d{1,2})\).*$/;
var aOffset = parseFloat(a.label.replace(re, '$1.$2'));
var bOffset = parseFloat(b.label.replace(re, '$1.$2'));
return aOffset < bOffset ? -1 : aOffset > bOffset ? 1 : 0;
});
};
const array = [
{
"defaultOrder": 34,
"label": "(GMT-01:00) Cape Verde Islands",
"codeId": 1218,
"code": "CVT",
"codeDesc": "(GMT-01:00) Cape Verde Islands",
"codeQualifier": "Time_Zone_Cd"
},
{
"defaultOrder": 41,
"label": "(GMT 01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna",
"codeId": 297,
"code": "CET",
"codeDesc": "(GMT 01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna",
"codeQualifier": "Time_Zone_Cd"
},
{
"defaultOrder": 40,
"label": "(GMT) Monrovia, Reykjavik",
"codeId": 1220,
"code": "GMT02",
"codeDesc": "(GMT) Monrovia, Reykjavik",
"codeQualifier": "Time_Zone_Cd"
}
];
const r = SortTimezoneCompare(array);
console.log(r);
CodePudding user response:
The problem with your code is, you are not considering the case where you don't have
or -
right after GMT
, which results in NaN
.
const SortTimezoneCompare = (data) => {
return data.sort((a, b) => {
var re = /^\(GMT([ -]\d{1,2}):(\d{1,2})\).*$/g;
var matches = {
a: [...a.label.matchAll(re)],
b: [...b.label.matchAll(re)]
};
var aOffset = 0;
var bOffset = 0;parseFloat(b.label.replace(re, '$1.$2'));
if (matches.a.length > 0) // matched with - or
aOffset = parseFloat(`${matches.a[0][1]}.${matches.a[0][2]}`);
if (matches.b.length > 0) // matched with - or
bOffset = parseFloat(`${matches.b[0][1]}.${matches.b[0][2]}`);
//console.log(aOffset "--" bOffset);
return aOffset < bOffset ? -1 : aOffset > bOffset ? 1 : 0;
});
};
const array = [
{
"defaultOrder": 34,
"label": "(GMT-01:00) Cape Verde Islands",
"codeId": 1218,
"code": "CVT",
"codeDesc": "(GMT-01:00) Cape Verde Islands",
"codeQualifier": "Time_Zone_Cd"
},
{
"defaultOrder": 41,
"label": "(GMT 01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna",
"codeId": 297,
"code": "CET",
"codeDesc": "(GMT 01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna",
"codeQualifier": "Time_Zone_Cd"
},
{
"defaultOrder": 40,
"label": "(GMT) Monrovia, Reykjavik",
"codeId": 1220,
"code": "GMT02",
"codeDesc": "(GMT) Monrovia, Reykjavik",
"codeQualifier": "Time_Zone_Cd"
}
];
const r = SortTimezoneCompare(array);
console.log(r);