I tried the typical sort function and checked if item is string. But I get a very strange output. Tried multiple different approaches.
var arr = [{section: '12.2.a'},
{section: '12.2.b.iii'},
{section: '12.2.c'},
{section: '12'},
{section: '12A'},
{section: '12.3.b'},
{section: '12.3.c'},
{section: 'Q2'},
{section: 'Q32'},
{section: 'Q6'},
{section: 'Q5'}]
var arr2 = arr.sort(function(a, b) {
var nums1 = a.section.split(".");
var nums2 = b.section.split(".");
for (var i = 0; i < nums1.length; i++) {
if (nums2[i]) {
if (nums1[i] !== nums2[i]) {
if (isNaN(parseInt(nums1[i])) && isNaN(parseInt(nums2[i]))) {
return nums1[i].localeCompare(nums2[i]);
}
return parseInt(nums1[i]) - parseInt(nums2[i]);
}
} else {
return 1;
}
}
return -1;
});
Should I use localeCompare or is it possible to without ? Would like the output to be:
[
{section: '12'},
{section: '12A'},
{section: '12.2.a'},
{section: '12.2.b.iii'},
{section: '12.2.c'},
{section: '12.3.b'},
{section: '12.3.c'},
{section: 'Q2'},
{section: 'Q6'},
{section: 'Q5'}
{section: 'Q32'}]
Would much appreciate any suggestions