Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting version numbers stored as string in an array

Say I have an array like this:

let arr = ["1.2.5", "1", "10", "2.0.4", "3.3.3.3"];

What would be the best way to sort this and get result like this:
let arr = ["1", "1.2.5", "2.0.4", "3.3.3.3", "10"];

First I thought of converting each item in the array into 'float' may work but then multiple decimals won't give expected results.

I can also go for a for loop and doing stuff like item.split(".") and then check one by one, but I do not think this is the best way.

Any suggestions, please?

like image 630
Tushar Shukla Avatar asked Sep 12 '25 07:09

Tushar Shukla


2 Answers

You could use String#localeCompare with options

sensitivity

Which differences in the strings should lead to non-zero result values. Possible values are:

  • "base": Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A.
  • "accent": Only strings that differ in base letters or accents and other diacritic marks compare as unequal. Examples: a ≠ b, a ≠ á, a = A.
  • "case": Only strings that differ in base letters or case compare as unequal. Examples: a ≠ b, a = á, a ≠ A.
  • "variant": Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal. Other differences may also be taken into consideration. Examples: a ≠ b, a ≠ á, a ≠ A.

The default is "variant" for usage "sort"; it's locale dependent for usage "search".

numeric

Whether numeric collation should be used, such that "1" < "2" < "10". Possible values are true and false; the default is false. This option can be set through an options property or through a Unicode extension key; if both are provided, the options property takes precedence. Implementations are not required to support this property.

var array = ["1.2.5", "1", "10", "2.0.4", "3.3.3.3"];

array.sort(function (a,b) {
    return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
});

console.log(array);
like image 82
Nina Scholz Avatar answered Sep 14 '25 21:09

Nina Scholz


function compare(a, b) {
    var aSplit = a.split(".");
    var bSplit = b.split(".");


    var length = Math.min(aSplit.length, bSplit.length);
    for (var i = 0; i < length; ++i) {
        if (parseInt(aSplit[i]) < parseInt(bSplit[i])) {
            return -1;
        } else if (parseInt(aSplit[i]) > parseInt(bSplit[i])) {
            return 1;
        }
    }

    if (aSplit.length < bSplit.length) {
        return -1;
    } else if (aSplit.length > bSplit.length) {
        return 1;
    }

    return 0;
}

You can use it like: arr.sort((a, b) => compare(a, b));

like image 34
Rishabh Makhija Avatar answered Sep 14 '25 20:09

Rishabh Makhija