JSFiddle - React, Tailwind, and code Playground

Sorting number with decimal places

by Nalin Sajwan

JavaScript

var qtStructure = [
    "5-5-9",
    "5-5-10",
    "5-5-5",
    "1",
    "2",
    "3",
    "4",
    "5",
    "1",
    "2",
    "3",
    "4",
    "5",
    "1-1-1",
    "2-1-1",
    "5-11",
    "5-10",
    "5-9",
    "5-8",
    "5-7",
    "5-6",
    "5-5",
    "5-4",
    "5-3",
    "5-2",
    "5-1",
    "4-2",
    "4-1",
    "3-2",
    "3-1",
    "2-1",
    "1-1"
];

var sorted = qtStructure.sort(function(a, b) {  
    var aSplitted = a.split("-");
    var bSplitted = b.split("-");
  
    var retunValue = 0;
  
    if(aSplitted.length == bSplitted.length){
        var value1 = a.toLowerCase();
        var value2 = b.toLowerCase();
      
        var nums1 = value1.split("-");
        var nums2 = value2.split("-");

        for (var i = 0; i < nums1.length; i++) {
            if (nums2[i]) { // assuming 5..2 is invalid
                if (nums1[i] !== nums2[i]) {
                   retunValue = nums1[i] - nums2[i];
                   break;
                } // else continue
            } else {
                retunValue = 1; // no second number in b
                break;
            }
        };
    } else {
        if(aSplitted.length > bSplitted.length) {
            retunValue = 1;
        } else {
            retunValue = -1;
        }
    }    
    return retunValue;
});

console.log("sorted ==> ", JSON.stringify(sorted, null, 4));