Say I have an array like this:
let arr = ["1.2.5", "1", "10", "2.0.4", "3.3.3.3"];
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?
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
trueandfalse; the default isfalse. This option can be set through an options property or through a Unicode extension key; if both are provided, theoptionsproperty 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);
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With