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 Existing Question Suggested by community. But it dealt with plain arrays instead of array of objects. I can tweak the answer as per needs. But the solutions seems to be pretty long. So I'm looking for a much simpler solutions.
Example Object:
my_list = [{"xxx": "9.6", "no_of_occurrence": 1 }, {"xxx": "9.2", "no_of_occurrence": 1},
{"xxx": "9.11", "no_of_occurrence": 1}, {"xxx": "9.10", "no_of_occurrence": 1}]
After sorting My desired output should be
Either
[{"xxx": "9.11", "no_of_occurrence": 1 }, {"xxx": "9.10", "no_of_occurrence": 1},
{"xxx": "9.6", "no_of_occurrence": 1}, {"xxx": "9.2", "no_of_occurrence": 1}]
or
[{"xxx": "9.2", "no_of_occurrence": 1 }, {"xxx": "9.6", "no_of_occurrence": 1},
{"xxx": "9.10", "no_of_occurrence": 1}, {"xxx": "9.11", "no_of_occurrence": 1}]
To achieve this I'm facing some issues. The decimal places are not treated the way they should be.
What I've tried so far is:
Approach 1:
my_list.sort((a, b) =>
{
if (a['xxx'] < b['xxx']) {
return -1;
}
if (a['xxx'] > b['xxx']) {
return 1;
}
return 0;
}
);
Approach 2:
my_list.sort((a, b) => {a['xxx'] - b['xxx']});
I did tried converting the string to float by using the "parseFloat(a['xxx'])" and "parseFloat(a['xxx']).toFixed(2)" as well. But nothing seems to be working.
The output generated by the above sort functions is:
[{
no_of_occurrence: 1,
xxx: "9.6"
}, {
no_of_occurrence: 1,
xxx: "9.2"
}, {
no_of_occurrence: 1,
xxx: "9.11"
}, {
no_of_occurrence: 1,
xxx: "9.10"
}]
However I tried, I'm not able to achieve what I desired. How can I treat the 9.10 is greater than 9.2? I know javascript treats 9.10 as 9.1 vise versa. But the data I received from the client and the client expectation is 9.10 is > 9.2.
Your help is appreciated.