I have an array of objects in that I want to sort the array based on the xxx version number string. But it seems there is an issue in sorting the order as per my desire.
I have seen the existing solutions for example, the 
CodePudding user response:
How can I treat the 9.10 is greater than 9.2?
Here you are not considering them as regular floating values. So if you ignore the ., you can easily compare them.
Try this one
my_list.sort((a, b) => {
const _a = a['xxx'].split('.')
const _b = b['xxx'].split('.')
if (Number(_a[0]) < Number(_b[0])) {
return -1;
}
if (Number(_a[0]) > Number(_b[0])) {
return 1;
}
if (Number(_a[1]) < Number(_b[1])) {
return -1;
}
if (Number(_a[1]) > Number(_b[1])) {
return 1;
}
return 0;
});
CodePudding user response:
Here is a generic solution
let my_list = [
{"xxx": "9.6", "no_of_occurrence": 1 },
{"xxx": "9.2", "no_of_occurrence": 1},
{"xxx": "9.11.3", "no_of_occurrence": 1},
{"xxx": "9.11.1", "no_of_occurrence": 1},
{"xxx": "9.10", "no_of_occurrence": 1}
];
my_list.sort((a, b) => {
let va = a.xxx.split("."), vb = b.xxx.split("."), i = 0
while(i < va.length && i < vb.length && ( va[i]) == ( vb[i]))
i ;
return ( va[i]) - ( vb[i]);
})
console.log(my_list)
