How to compare software version number using js? (only number)

JavascriptSorting

Javascript Problem Overview


Here is the software version number:

"1.0", "1.0.1", "2.0", "2.0.0.1", "2.0.1"

How can I compare this?? Assume the correct order is:

"1.0", "1.0.1", "2.0", "2.0.0.1", "2.0.1"

The idea is simple...: Read the first digit, than, the second, after that the third.... But I can't convert the version number to float number.... You also can see the version number like this:

"1.0.0.0", "1.0.1.0", "2.0.0.0", "2.0.0.1", "2.0.1.0"

and this is more clear to see what is the idea behind... But, how to convert it into a computer program?? Do any one have any idea on how to sorting this? Thank you.

Javascript Solutions


Solution 1 - Javascript

The basic idea to make this comparison would be to use Array.split to get arrays of parts from the input strings and then compare pairs of parts from the two arrays; if the parts are not equal we know which version is smaller.

There are a few of important details to keep in mind:

  1. How should the parts in each pair be compared? The question wants to compare numerically, but what if we have version strings that are not made up of just digits (e.g. "1.0a")?
  2. What should happen if one version string has more parts than the other? Most likely "1.0" should be considered less than "1.0.1", but what about "1.0.0"?

Here's the code for an implementation that you can use directly (gist with documentation):

function versionCompare(v1, v2, options) {
    var lexicographical = options && options.lexicographical,
        zeroExtend = options && options.zeroExtend,
        v1parts = v1.split('.'),
        v2parts = v2.split('.');

    function isValidPart(x) {
        return (lexicographical ? /^\d+[A-Za-z]*$/ : /^\d+$/).test(x);
    }

    if (!v1parts.every(isValidPart) || !v2parts.every(isValidPart)) {
        return NaN;
    }

    if (zeroExtend) {
        while (v1parts.length < v2parts.length) v1parts.push("0");
        while (v2parts.length < v1parts.length) v2parts.push("0");
    }

    if (!lexicographical) {
        v1parts = v1parts.map(Number);
        v2parts = v2parts.map(Number);
    }

    for (var i = 0; i < v1parts.length; ++i) {
        if (v2parts.length == i) {
            return 1;
        }

        if (v1parts[i] == v2parts[i]) {
            continue;
        }
        else if (v1parts[i] > v2parts[i]) {
            return 1;
        }
        else {
            return -1;
        }
    }

    if (v1parts.length != v2parts.length) {
        return -1;
    }

    return 0;
}

This version compares parts naturally, does not accept character suffixes and considers "1.7" to be smaller than "1.7.0". The comparison mode can be changed to lexicographical and shorter version strings can be automatically zero-padded using the optional third argument.

There is a JSFiddle that runs "unit tests" here; it is a slightly expanded version of ripper234's work (thank you).

Important note: This code uses Array.map and Array.every, which means that it will not run in IE versions earlier than 9. If you need to support those you will have to provide polyfills for the missing methods.

Solution 2 - Javascript

semver

The semantic version parser used by npm.

$ npm install semver

var semver = require('semver');

semver.diff('3.4.5', '4.3.7') //'major'
semver.diff('3.4.5', '3.3.7') //'minor'
semver.gte('3.4.8', '3.4.7') //true
semver.ltr('3.4.8', '3.4.7') //false

semver.valid('1.2.3') // '1.2.3'
semver.valid('a.b.c') // null
semver.clean(' =v1.2.3 ') // '1.2.3'
semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true
semver.gt('1.2.3', '9.8.7') // false
semver.lt('1.2.3', '9.8.7') // true

var versions = [ '1.2.3', '3.4.5', '1.0.2' ]
var max = versions.sort(semver.rcompare)[0]
var min = versions.sort(semver.compare)[0]
var max = semver.maxSatisfying(versions, '*')

Semantic Versioning Link :
https://www.npmjs.com/package/semver#prerelease-identifiers<br>

Solution 3 - Javascript

// Return 1 if a > b
// Return -1 if a < b
// Return 0 if a == b
function compare(a, b) {
    if (a === b) {
       return 0;
    }

    var a_components = a.split(".");
    var b_components = b.split(".");

    var len = Math.min(a_components.length, b_components.length);

    // loop while the components are equal
    for (var i = 0; i < len; i++) {
        // A bigger than B
        if (parseInt(a_components[i]) > parseInt(b_components[i])) {
            return 1;
        }
    
        // B bigger than A
        if (parseInt(a_components[i]) < parseInt(b_components[i])) {
            return -1;
        }
    }

    // If one's a prefix of the other, the longer one is greater.
    if (a_components.length > b_components.length) {
        return 1;
    }

    if (a_components.length < b_components.length) {
        return -1;
    }

    // Otherwise they are the same.
    return 0;
}

console.log(compare("1", "2"));
console.log(compare("2", "1"));

console.log(compare("1.0", "1.0"));
console.log(compare("2.0", "1.0"));
console.log(compare("1.0", "2.0"));
console.log(compare("1.0.1", "1.0"));

Solution 4 - Javascript

This very small, yet very fast compare function takes version numbers of any length and any number size per segment.

Return values:

  • a number < 0 if a < b
  • a number > 0 if a > b
  • 0 if a = b

So you can use it as compare function for Array.sort();

EDIT: Bugfixed Version stripping trailing zeros to recognize "1" and "1.0.0" as equal

function cmpVersions (a, b) {
    var i, diff;
    var regExStrip0 = /(\.0+)+$/;
    var segmentsA = a.replace(regExStrip0, '').split('.');
    var segmentsB = b.replace(regExStrip0, '').split('.');
    var l = Math.min(segmentsA.length, segmentsB.length);

    for (i = 0; i < l; i++) {
        diff = parseInt(segmentsA[i], 10) - parseInt(segmentsB[i], 10);
        if (diff) {
            return diff;
        }
    }
    return segmentsA.length - segmentsB.length;
}

// TEST
console.log(
['2.5.10.4159', '1.0.0', '0.5', '0.4.1', '1', '1.1', '0.0.0', '2.5.0', '2', '0.0', '2.5.10', '10.5', '1.25.4', '1.2.15'].sort(cmpVersions));
// Result:
// ["0.0.0", "0.0", "0.4.1", "0.5", "1.0.0", "1", "1.1", "1.2.15", "1.25.4", "2", "2.5.0", "2.5.10", "2.5.10.4159", "10.5"]

Solution 5 - Javascript

The simplest is to use localeCompare :

a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })

This will return:

  • 0: version strings are equal
  • 1: version a is greater than b
  • -1: version b is greater than a

Solution 6 - Javascript

Simple and short function:

function isNewerVersion (oldVer, newVer) {
  const oldParts = oldVer.split('.')
  const newParts = newVer.split('.')
  for (var i = 0; i < newParts.length; i++) {
    const a = ~~newParts[i] // parse int
    const b = ~~oldParts[i] // parse int
    if (a > b) return true
    if (a < b) return false
  }
  return false
}

Tests:

isNewerVersion('1.0', '2.0') // true
isNewerVersion('1.0', '1.0.1') // true
isNewerVersion('1.0.1', '1.0.10') // true
isNewerVersion('1.0.1', '1.0.1') // false
isNewerVersion('2.0', '1.0') // false
isNewerVersion('2', '1.0') // false
isNewerVersion('2.0.0.0.0.1', '2.1') // true
isNewerVersion('2.0.0.0.0.1', '2.0') // false

Solution 7 - Javascript

Taken from http://java.com/js/deployJava.js:

    // return true if 'installed' (considered as a JRE version string) is
    // greater than or equal to 'required' (again, a JRE version string).
    compareVersions: function (installed, required) {

        var a = installed.split('.');
        var b = required.split('.');

        for (var i = 0; i < a.length; ++i) {
            a[i] = Number(a[i]);
        }
        for (var i = 0; i < b.length; ++i) {
            b[i] = Number(b[i]);
        }
        if (a.length == 2) {
            a[2] = 0;
        }

        if (a[0] > b[0]) return true;
        if (a[0] < b[0]) return false;

        if (a[1] > b[1]) return true;
        if (a[1] < b[1]) return false;

        if (a[2] > b[2]) return true;
        if (a[2] < b[2]) return false;

        return true;
    }

Solution 8 - Javascript

Couldn't find a function doing what I wanted here. So I wrote my own. This is my contribution. I hope someone find it useful.

Pros:

  • Handles version strings of arbitrary length. '1' or '1.1.1.1.1'.

  • Defaults each value to 0 if not specified. Just because a string is longer doesn't mean it's a bigger version. ('1' should be the same as '1.0' and '1.0.0.0'.)

  • Compare numbers not strings. ('3'<'21' should be true. Not false.)

  • Don't waste time on useless compares in the loop. (Comparing for ==)

  • You can choose your own comparator.

Cons:

  • It does not handle letters in the version string. (I don't know how that would even work?)

My code, similar to the accepted answer by Jon:

function compareVersions(v1, comparator, v2) {
	"use strict";
	var comparator = comparator == '=' ? '==' : comparator;
	if(['==','===','<','<=','>','>=','!=','!=='].indexOf(comparator) == -1) {
		throw new Error('Invalid comparator. ' + comparator);
	}
	var v1parts = v1.split('.'), v2parts = v2.split('.');
	var maxLen = Math.max(v1parts.length, v2parts.length);
	var part1, part2;
	var cmp = 0;
	for(var i = 0; i < maxLen && !cmp; i++) {
		part1 = parseInt(v1parts[i], 10) || 0;
		part2 = parseInt(v2parts[i], 10) || 0;
		if(part1 < part2)
			cmp = 1;
		if(part1 > part2)
			cmp = -1;
	}
	return eval('0' + comparator + cmp);
}

Examples:

compareVersions('1.2.0', '==', '1.2'); // true
compareVersions('00001', '==', '1.0.0'); // true
compareVersions('1.2.0', '<=', '1.2'); // true
compareVersions('2.2.0', '<=', '1.2'); // false

Solution 9 - Javascript

Here is another short version that works with any number of sub versions, padded zeros and even numbers with letters (1.0.0b3)

const compareVer = ((prep, repl) =>
{
  repl = c => "." + ((c = c.replace(/[\W_]+/, "")) ? c.toLowerCase().charCodeAt(0) - 65536 : "") + ".";
  prep = t => ("" + t)
      //treat non-numerical characters as lower version
      //replacing them with a negative number based on charcode of first character
    .replace(/[^0-9\.]+/g, repl)
      //remove trailing "." and "0" if followed by non-numerical characters (1.0.0b);
    .replace(/(?:\.0+)*(\.-[0-9]+)(\.[0-9]+)?\.*$/g, "$1$2")
    .split('.');

  return (a, b, c, i, r) =>
  {
    a = prep(a);
    b = prep(b);
    for (i = 0, r = 0, c = Math.max(a.length, b.length); i < c && !r; i++)
    {
      r = -1 * ((a[i] = ~~a[i]) < (b[i] = ~~b[i])) + (a[i] > b[i]);
    }
    return r;
  }
})();

Function returns:

0 if a = b

1 if a > b

-1 if a < b

1.0         = 1.0.0.0.0.0
1.0         < 1.0.1
1.0b1       < 1.0
1.0b        = 1.0b
1.1         > 1.0.1b
1.1alpha    < 1.1beta
1.1rc1      > 1.1beta
1.1rc1      < 1.1rc2
1.1.0a1     < 1.1a2
1.1.0a10    > 1.1.0a1
1.1.0alpha  = 1.1a
1.1.0alpha2 < 1.1b1
1.0001      > 1.00000.1.0.0.0.01

/*use strict*/
const compareVer = ((prep, repl) =>
{
  repl = c => "." + ((c = c.replace(/[\W_]+/, "")) ? c.toLowerCase().charCodeAt(0) - 65536 : "") + ".";
  prep = t => ("" + t)
      //treat non-numerical characters as lower version
      //replacing them with a negative number based on charcode of first character
    .replace(/[^0-9\.]+/g, repl)
      //remove trailing "." and "0" if followed by non-numerical characters (1.0.0b);
    .replace(/(?:\.0+)*(\.-[0-9]+)(\.[0-9]+)?\.*$/g, "$1$2")
    .split('.');

  return (a, b, c, i, r) =>
  {
    a = prep(a);
    b = prep(b);
    for (i = 0, r = 0, c = Math.max(a.length, b.length); i < c && !r; i++)
    {
      r = -1 * ((a[i] = ~~a[i]) < (b[i] = ~~b[i])) + (a[i] > b[i]);
    }
    return r;
  }
})();

//examples

let list = [  ["1.0",         "1.0.0.0.0.0"],
  ["1.0",         "1.0.1"],
  ["1.0b1",       "1.0"],
  ["1.0b",        "1.0b"],
  ["1.1",         "1.0.1b"],
  ["1.1alpha",    "1.1beta"],
  ["1.1rc1",      "1.1beta"],
  ["1.1rc1",      "1.1rc2"],
  ["1.1.0a1",     "1.1a2"],
  ["1.1.0a10",    "1.1.0a1"],
  ["1.1.0alpha",  "1.1a"],
  ["1.1.0alpha2", "1.1b1"],
  ["1.0001",      "1.00000.1.0.0.0.01"]
]
for(let i = 0; i < list.length; i++)
{
  console.log( list[i][0] + " " + "<=>"[compareVer(list[i][0], list[i][1]) + 1] + " " + list[i][1] );
}

https://jsfiddle.net/vanowm/p7uvtbor/

Solution 10 - Javascript

I faced the similar issue, and I had already created a solution for it. Feel free to give it a try.

It returns 0 for equal, 1 if the version is greater and -1 if it is less

function compareVersion(currentVersion, minVersion) {
  let current = currentVersion.replace(/\./g," .").split(' ').map(x=>parseFloat(x,10))
  let min = minVersion.replace(/\./g," .").split(' ').map(x=>parseFloat(x,10))

  for(let i = 0; i < Math.max(current.length, min.length); i++) {
    if((current[i] || 0) < (min[i] || 0)) {
      return -1
    } else if ((current[i] || 0) > (min[i] || 0)) {
      return 1
    }
  }
  return 0
}


console.log(compareVersion("81.0.1212.121","80.4.1121.121"));
console.log(compareVersion("81.0.1212.121","80.4.9921.121"));
console.log(compareVersion("80.0.1212.121","80.4.9921.121"));
console.log(compareVersion("4.4.0","4.4.1"));
console.log(compareVersion("5.24","5.2"));
console.log(compareVersion("4.1","4.1.2"));
console.log(compareVersion("4.1.2","4.1"));
console.log(compareVersion("4.4.4.4","4.4.4.4.4"));
console.log(compareVersion("4.4.4.4.4.4","4.4.4.4.4"));
console.log(compareVersion("0","1"));
console.log(compareVersion("1","1"));
console.log(compareVersion("1","1.0.00000.0000"));
console.log(compareVersion("","1"));
console.log(compareVersion("10.0.1","10.1"));

Solution 11 - Javascript

2017 answer:

v1 = '20.0.12'; 
v2 = '3.123.12';

compareVersions(v1,v2) 
// return positive: v1 > v2, zero:v1 == v2, negative: v1 < v2 
function compareVersions(v1, v2) {
        v1= v1.split('.')
        v2= v2.split('.')
        var len = Math.max(v1.length,v2.length)
		/*default is true*/
        for( let i=0; i < len; i++)
			v1 = Number(v1[i] || 0);
            v2 = Number(v2[i] || 0);
			if (v1 !== v2) return v1 - v2 ;
			i++;
		}
		return 0;
	}

Simplest code for modern browsers:

 function compareVersion2(ver1, ver2) {
      ver1 = ver1.split('.').map( s => s.padStart(10) ).join('.');
      ver2 = ver2.split('.').map( s => s.padStart(10) ).join('.');
      return ver1 <= ver2;
 }

The idea here is to compare numbers but in the form of string. to make the comparison work the two strings must be at the same length. so:

"123" > "99" become "123" > "099"
padding the short number "fix" the comparison

Here I padding each part with zeros to lengths of 10. then just use simple string compare for the answer

Example :

var ver1 = '0.2.10', ver2=`0.10.2`
//become 
ver1 = '0000000000.0000000002.0000000010'
ver2 = '0000000000.0000000010.0000000002'
// then it easy to see that
ver1 <= ver2 // true

Solution 12 - Javascript

Forgive me if this idea already been visited in a link I have not seen.

I have had some success with conversion of the parts into a weighted sum like so:

partSum = this.major * Math.Pow(10,9);
partSum += this.minor * Math.Pow(10, 6);
partSum += this.revision * Math.Pow(10, 3);
partSum += this.build * Math.Pow(10, 0);

Which made comparisons very easy (comparing a double). Our version fields are never more than 4 digits.

7.10.2.184  -> 7010002184.0
7.11.0.1385 -> 7011001385.0

I hope this helps someone, as the multiple conditionals seem a bit overkill.

Solution 13 - Javascript

Although this question already has a lot of answers, each one promotes their own backyard-brewn solution, whilst we have a whole ecosystem of (battle-)tested libraries for this.

A quick search on NPM, GitHub, X will give us some lovely libs, and I'd want to run through some:

semver-compare is a great lightweight (~230B) lib that's especially useful if you want to sort by version numbers, as the library's exposed method returns -1, 0 or 1 appropriately.

The core of the lib:

module.exports = function cmp (a, b) {
    var pa = a.split('.');
    var pb = b.split('.');
    for (var i = 0; i < 3; i++) {
        var na = Number(pa[i]);
        var nb = Number(pb[i]);
        if (na > nb) return 1;
        if (nb > na) return -1;
        if (!isNaN(na) && isNaN(nb)) return 1;
        if (isNaN(na) && !isNaN(nb)) return -1;
    }
    return 0;
};

compare-semver is rather hefty in size (~4.4kB gzipped), but allows for some nice unique comparisons like to find the min/max of a stack of versions or to find out if the provided version is unique or less than anything else in a collection of versions.

compare-versions is another small lib (~630B gzipped) and follows the spec nicely, meaning you can compare versions with alpha/beta flags and even wildcards (like for minor/patch versions: 1.0.x or 1.0.*)

Point being: there's not always a need to copy-paste code from StackOverflow, if you can find decent, (unit-)tested versions via your package manager of choice.

Solution 14 - Javascript

Check the function version_compare() from the php.js project. It's is similar to PHP's version_compare().

You can simply use it like this:

version_compare('2.0', '2.0.0.1', '<'); 
// returns true

Solution 15 - Javascript

My less verbose answer than most of the answers here

/**
 * Compare two semver versions. Returns true if version A is greater than
 * version B
 * @param {string} versionA
 * @param {string} versionB
 * @returns {boolean}
 */
export const semverGreaterThan = function(versionA, versionB){
  var versionsA = versionA.split(/\./g),
    versionsB = versionB.split(/\./g)
  while (versionsA.length || versionsB.length) {
    var a = Number(versionsA.shift()), b = Number(versionsB.shift())
    if (a == b)
      continue
    return (a > b || isNaN(b))
  }
  return false
}

Solution 16 - Javascript

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 versions = ["2.0.1", "2.0", "1.0", "1.0.1", "2.0.0.1"];

versions.sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }));

console.log(versions);

Solution 17 - Javascript

The (most of the time) correct JavaScript answer in 2020

Both Nina Scholz in March 2020 and Sid Vishnoi in April 2020 post the modern answer:

var versions = ["2.0.1", "2.0", "1.0", "1.0.1", "2.0.0.1"];

versions.sort((a, b) => 
   a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })
);

console.log(versions);

localCompare has been around for some time

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator

But what about 1.0a and 1.0.1

localCompare doesn't solve that, still returns 1.0.1 , 1.0a

Michael Deal in his (longish &complex) solution already cracked that in 2013

He converts Numbers to another Base, so they can be sorted better

His answer got me thinking...

666 - Don't think in numbers - 999

Sorting is alphanumeric, based on the ASCII values, so let's (ab)use ASCII as the "base"

My solution is to convert 1.0.2.1 to b.a.c.b to bacb , and then sort

This solves 1.1 vs. 1.0.0.0.1 with: bb vs. baaab

And immediately solves the 1.0a and 1.0.1 sorting problem with notation: baa and bab

Conversion is done with:

    const str = s => s.match(/(\d+)|[a-z]/g)
                      .map(c => c == ~~c ? String.fromCharCode(97 + c) : c);

= Calculate ASCII value for 0...999 Numbers, otherwise concat letter

1.0a >>> [ "1" , "0" , "a" ] >>> [ "b" , "a" , "a" ]

For comparison sake there is no need to concatenate it to one string with .join("")

Oneliner
const sortVersions=(x,v=s=>s.match(/(\d+)|[a-z]/g)
                            .map(c=>c==~~c?String.fromCharCode(97+c):c))
                    =>x.sort((a,b)=>v(b)<v(a)?1:-1)
Test snippet:

function log(label,val){
  document.body.append(label,String(val).replace(/,/g," - "),document.createElement("BR"));
}

let v = ["1.90.1", "1.9.1", "1.89", "1.090", "1.2", "1.0a", "1.0.1", "1.10", "1.0.0a"];
log('not sorted input :',v);

v.sort((a, b) => a.localeCompare(b,undefined,{numeric:true,sensitivity:'base'   }));
log(' locale Compare :', v); // 1.0a AFTER 1.0.1

const str = s => s.match(/(\d+)|[a-z]/g)
                  .map(c => c == ~~c ? String.fromCharCode(97 + c) : c);
const versionCompare = (a, b) => {
  a = str(a);
  b = str(b);
  return b < a ? 1 : a == b ? 0 : -1;
}

v.sort(versionCompare);
log('versionCompare:', v);

Note how 1.090 is sorted in both results.

My code will not solve the 001.012.001 notation mentioned in one answer, but the localeCompare gets that part of the challenge right.

You could combine the two methods:

  • sort with .localCompare OR versionCompare when there is a letter involved

Final JavaScript solution

const sortVersions = (
  x,
  v = s => s.match(/[a-z]|\d+/g).map(c => c==~~c ? String.fromCharCode(97 + c) : c)
) => x.sort((a, b) => (a + b).match(/[a-z]/) 
                             ? v(b) < v(a) ? 1 : -1 
                             : a.localeCompare(b, 0, {numeric: true}))

let v=["1.90.1","1.090","1.0a","1.0.1","1.0.0a","1.0.0b","1.0.0.1"];
console.log(sortVersions(v));

Solution 18 - Javascript

Dead simple way:

function compareVer(previousVersion, currentVersion) {
 try {
    const [prevMajor, prevMinor = 0, prevPatch = 0] = previousVersion.split('.').map(Number);
    const [curMajor, curMinor = 0, curPatch = 0] = currentVersion.split('.').map(Number);

    if (curMajor > prevMajor) {
      return 'major update';
    }
    if (curMajor < prevMajor) {
      return 'major downgrade';
    }
    if (curMinor > prevMinor) {
      return 'minor update';
    }
    if (curMinor < prevMinor) {
      return 'minor downgrade';
    }
    if (curPatch > prevPatch) {
      return 'patch update';
    }
    if (curPatch < prevPatch) {
      return 'patch downgrade';
    }
    return 'same version';
  } catch (e) {
    return 'invalid format';
  }
}

Output:

compareVer("3.1", "3.1.1") // patch update
compareVer("3.1.1", "3.2") // minor update
compareVer("2.1.1", "1.1.1") // major downgrade
compareVer("1.1.1", "1.1.1") // same version

Solution 19 - Javascript

We can now use Intl.Collator API now to create numeric comparators. Browser support is pretty decent, but not supported in Node.js at the time of writing.

const semverCompare = new Intl.Collator("en", { numeric: true }).compare;

const versions = ['1.0.1', '1.10.2', '1.1.1', '1.10.1', '1.5.10', '2.10.0', '2.0.1'];

console.log(versions.sort(semverCompare))

const example2 = ["1.0", "1.0.1", "2.0", "2.0.0.1", "2.0.1"];
console.log(example2.sort(semverCompare))

Solution 20 - Javascript

you can use Javascript localeCompare method

a.localeCompare(b, undefined, { numeric: true })

here is an example:

"1.1".localeCompare("2.1.1", undefined, { numeric: true }) => -1

"1.0.0".localeCompare("1.0", undefined, { numeric: true }) => 1

"1.0.0".localeCompare("1.0.0", undefined, { numeric: true }) => 0

Solution 21 - Javascript

The idea is comparate two versions and know which is the biggest. We delete "." and we compare each position of the vector with the other.

// Return 1  if a > b
// Return -1 if a < b
// Return 0  if a == b

function compareVersions(a_components, b_components) {

   if (a_components === b_components) {
       return 0;
   }

   var partsNumberA = a_components.split(".");
   var partsNumberB = b_components.split(".");

   for (var i = 0; i < partsNumberA.length; i++) {

      var valueA = parseInt(partsNumberA[i]);
      var valueB = parseInt(partsNumberB[i]);
 
      // A bigger than B
      if (valueA > valueB || isNaN(valueB)) {
         return 1;
      }

      // B bigger than A
      if (valueA < valueB) {
         return -1;
      }
   }
}

Solution 22 - Javascript

// Returns true if v1 is bigger than v2, and false if otherwise.
function isNewerThan(v1, v2) {
      v1=v1.split('.');
      v2=v2.split('.');
      for(var i = 0; i<Math.max(v1.length,v2.length); i++){
      	if(v1[i] == undefined) return false; // If there is no digit, v2 is automatically bigger
        if(v2[i] == undefined) return true; // if there is no digit, v1 is automatically bigger
      	if(v1[i] > v2[i]) return true;
        if(v1[i] < v2[i]) return false;
      }
      return false; // Returns false if they are equal
    }

Solution 23 - Javascript

Few lines of code and good if you don't want to allow letters or symbols. This works if you control the versioning scheme and it's not something a 3rd party provides.

// we presume all versions are of this format "1.4" or "1.10.2.3", without letters
// returns: 1 (bigger), 0 (same), -1 (smaller)
function versionCompare (v1, v2) {
  const v1Parts = v1.split('.')
  const v2Parts = v2.split('.')
  const length = Math.max(v1Parts.length, v2Parts.length)
  for (let i = 0; i < length; i++) {
    const value = (parseInt(v1Parts[i]) || 0) - (parseInt(v2Parts[i]) || 0)
    if (value < 0) return -1
    if (value > 0) return 1
  }
  return 0
}

console.log(versionCompare('1.2.0', '1.2.4') === -1)
console.log(versionCompare('1.2', '1.2.0') === 0)
console.log(versionCompare('1.2', '1') === 1)
console.log(versionCompare('1.2.10', '1.2.1') === 1)
console.log(versionCompare('1.2.134230', '1.2.2') === 1)
console.log(versionCompare('1.2.134230', '1.3.0.1.2.3.1') === -1)

Solution 24 - Javascript

The replace() function only replaces the first occurence in the string. So, lets replace the . with ,. Afterwards delete all . and make the , to . again and parse it to float.

for(i=0; i<versions.length; i++) {
	v = versions[i].replace('.', ',');
	v = v.replace(/\./g, '');
	versions[i] = parseFloat(v.replace(',', '.'));
}

finally, sort it:

versions.sort();

Solution 25 - Javascript

Check out this blog post. This function works for numeric version numbers.

function compVersions(strV1, strV2) {
  var nRes = 0
    , parts1 = strV1.split('.')
    , parts2 = strV2.split('.')
    , nLen = Math.max(parts1.length, parts2.length);

  for (var i = 0; i < nLen; i++) {
    var nP1 = (i < parts1.length) ? parseInt(parts1[i], 10) : 0
      , nP2 = (i < parts2.length) ? parseInt(parts2[i], 10) : 0;

    if (isNaN(nP1)) { nP1 = 0; }
    if (isNaN(nP2)) { nP2 = 0; }

    if (nP1 != nP2) {
      nRes = (nP1 > nP2) ? 1 : -1;
      break;
    }
  }
 
  return nRes;
};

compVersions('10', '10.0'); // 0
compVersions('10.1', '10.01.0'); // 0
compVersions('10.0.1', '10.0'); // 1
compVersions('10.0.1', '10.1'); // -1

Solution 26 - Javascript

If, for example, we want to check if the current jQuery version is less than 1.8, parseFloat($.ui.version) < 1.8 ) would give a wrong result if version is "1.10.1", since parseFloat("1.10.1") returns 1.1. A string compare would also go wrong, since "1.8" < "1.10" evaluates to false.

So we need a test like this

if(versionCompare($.ui.version, "1.8") < 0){
    alert("please update jQuery");
}

The following function handles this correctly:

/** Compare two dotted version strings (like '10.2.3').
 * @returns {Integer} 0: v1 == v2, -1: v1 < v2, 1: v1 > v2
 */
function versionCompare(v1, v2) {
    var v1parts = ("" + v1).split("."),
        v2parts = ("" + v2).split("."),
        minLength = Math.min(v1parts.length, v2parts.length),
        p1, p2, i;
    // Compare tuple pair-by-pair. 
    for(i = 0; i < minLength; i++) {
        // Convert to integer if possible, because "8" > "10".
        p1 = parseInt(v1parts[i], 10);
        p2 = parseInt(v2parts[i], 10);
        if (isNaN(p1)){ p1 = v1parts[i]; } 
        if (isNaN(p2)){ p2 = v2parts[i]; } 
        if (p1 == p2) {
            continue;
        }else if (p1 > p2) {
            return 1;
        }else if (p1 < p2) {
            return -1;
        }
        // one operand is NaN
        return NaN;
    }
    // The longer tuple is always considered 'greater'
    if (v1parts.length === v2parts.length) {
        return 0;
    }
    return (v1parts.length < v2parts.length) ? -1 : 1;
}

Here are some examples:

// compare dotted version strings
console.assert(versionCompare("1.8",      "1.8.1")    <   0);
console.assert(versionCompare("1.8.3",    "1.8.1")    >   0);
console.assert(versionCompare("1.8",      "1.10")     <   0);
console.assert(versionCompare("1.10.1",   "1.10.1")   === 0);
// Longer is considered 'greater'
console.assert(versionCompare("1.10.1.0", "1.10.1")   >   0);
console.assert(versionCompare("1.10.1",   "1.10.1.0") <   0);
// Strings pairs are accepted
console.assert(versionCompare("1.x",      "1.x")      === 0);
// Mixed int/string pairs return NaN
console.assert(isNaN(versionCompare("1.8", "1.x")));
//works with plain numbers
console.assert(versionCompare("4", 3)   >   0);

See here for a live sample and test suite: http://jsfiddle.net/mar10/8KjvP/

Solution 27 - Javascript

This is a neat trick. If you are dealing with numeric values, between a specific range of values, you can assign a value to each level of the version object. For instance "largestValue" is set to 0xFF here, which creates a very "IP" sort of look to your versioning.

This also handles alpha-numeric versioning (i.e. 1.2a < 1.2b)

// The version compare function
function compareVersion(data0, data1, levels) {
    function getVersionHash(version) {
        var value = 0;
        version = version.split(".").map(function (a) {
            var n = parseInt(a);
            var letter = a.replace(n, "");
            if (letter) {
                return n + letter[0].charCodeAt() / 0xFF;
            } else {
    			return n;
            }
		});
	    for (var i = 0; i < version.length; ++i) {
            if (levels === i) break;
            value += version[i] / 0xFF * Math.pow(0xFF, levels - i + 1);
        }
        return value;
    };
    var v1 = getVersionHash(data0);
    var v2 = getVersionHash(data1);
    return v1 === v2 ? -1 : v1 > v2 ? 0 : 1;
};
// Returns 0 or 1, correlating to input A and input B
// Direct match returns -1
var version = compareVersion("1.254.253", "1.254.253a", 3);

Solution 28 - Javascript

I made this based on Kons idea, and optimized it for Java version "1.7.0_45". It's just a function meant to convert a version string to a float. This is the function:

function parseVersionFloat(versionString) {
	var versionArray = ("" + versionString)
			.replace("_", ".")
			.replace(/[^0-9.]/g, "")
			.split("."),
		sum = 0;
	for (var i = 0; i < versionArray.length; ++i) {
		sum += Number(versionArray[i]) / Math.pow(10, i * 3);
	}
	console.log(versionString + " -> " + sum);
	return sum;
}

String "1.7.0_45" is converted to 1.0070000450000001 and this is good enough for a normal comparison. Error explained here: https://stackoverflow.com/questions/1458633/elegant-workaround-for-javascript-floating-point-number-problem. If need more then 3 digits on any part you can change the divider Math.pow(10, i * 3);.

Output will look like this:

1.7.0_45         > 1.007000045
ver 1.7.build_45 > 1.007000045
1.234.567.890    > 1.23456789

Solution 29 - Javascript

Here's a coffeescript implementation suitable for use with Array.sort inspired by other answers here:

# Returns > 0 if v1 > v2 and < 0 if v1 < v2 and 0 if v1 == v2
compareVersions = (v1, v2) ->
  v1Parts = v1.split('.')
  v2Parts = v2.split('.')
  minLength = Math.min(v1Parts.length, v2Parts.length)
  if minLength > 0
    for idx in [0..minLength - 1]
      diff = Number(v1Parts[idx]) - Number(v2Parts[idx])
      return diff unless diff is 0
  return v1Parts.length - v2Parts.length

Solution 30 - Javascript

I wrote a node module for sorting versions, you can find it here: version-sort

Features:

  • no limit of sequences '1.0.1.5.53.54654.114.1.154.45' works
  • no limit of sequence length: '1.1546515465451654654654654138754431574364321353734' works
  • can sort objects by version (see README)
  • stages (like alpha, beta, rc1, rc2)

Do not hesitate to open an issue if you need an other feature.

Solution 31 - Javascript

This works for numeric versions of any length separated by a period. It returns true only if myVersion is >= minimumVersion, making the assumption that version 1 is less than 1.0, version 1.1 is less than 1.1.0 and so on. It should be fairly simple to add extra conditions such as accepting numbers (just convert to a string) and hexadecimal or making the delimiter dynamic (just add a delimiter parameter then replace the "." with the param)

function versionCompare(myVersion, minimumVersion) {
	
	var v1 = myVersion.split("."), v2 = minimumVersion.split("."), minLength;	
	
	minLength= Math.min(v1.length, v2.length);
	
	for(i=0; i<minLength; i++) {
		if(Number(v1[i]) > Number(v2[i])) {
			return true;
		}
		if(Number(v1[i]) < Number(v2[i])) {
			return false;
		}			
	}
	
	return (v1.length >= v2.length);
}

Here are some tests:

console.log(versionCompare("4.4.0","4.4.1"));
console.log(versionCompare("5.24","5.2"));
console.log(versionCompare("4.1","4.1.2"));
console.log(versionCompare("4.1.2","4.1"));
console.log(versionCompare("4.4.4.4","4.4.4.4.4"));
console.log(versionCompare("4.4.4.4.4.4","4.4.4.4.4"));
console.log(versionCompare("0","1"));
console.log(versionCompare("1","1"));
console.log(versionCompare("","1"));
console.log(versionCompare("10.0.1","10.1"));

Alternatively here is a recursive version

function versionCompare(myVersion, minimumVersion) {
  return recursiveCompare(myVersion.split("."),minimumVersion.split("."),Math.min(myVersion.length, minimumVersion.length),0);
}

function recursiveCompare(v1, v2,minLength, index) {
  if(Number(v1[index]) < Number(v2[index])) {
	return false;
  }
  if(Number(v1[i]) < Number(v2[i])) {
	return true;
	}
  if(index === minLength) {
	return (v1.length >= v2.length);
  }
  return recursiveCompare(v1,v2,minLength,index+1);
}

Solution 32 - Javascript

couldnt you convert them into numbers and then sort after size? Append 0's to the ones to the numbers that are < 4 in length

played around in console:

$(["1.0.0.0", "1.0.1.0", "2.0.0.0", "2.0.0.1", "2.0.1", "3.0"]).each(function(i,e) {
    var n =   e.replace(/\./g,"");
    while(n.length < 4) n+="0" ; 
    num.push(  +n  )
});

bigger the version, the bigger number. Edit: probably needs adjusting to account for bigger version series

Solution 33 - Javascript

I like the version from @mar10, though from my point of view, there is a chance of misusage (seems it is not the case if versions are compatible with Semantic Versioning document, but may be the case if some "build number" is used):

versionCompare( '1.09', '1.1');  // returns 1, which is wrong:  1.09 < 1.1
versionCompare('1.702', '1.8');  // returns 1, which is wrong: 1.702 < 1.8

The problem here is that sub-numbers of version number are, in some cases, written with trailing zeroes cut out (at least as I recently see it while using different software), which is similar to rational part of a number, so:

5.17.2054 > 5.17.2
5.17.2 == 5.17.20 == 5.17.200 == ... 
5.17.2054 > 5.17.20
5.17.2054 > 5.17.200
5.17.2054 > 5.17.2000
5.17.2054 > 5.17.20000
5.17.2054 < 5.17.20001
5.17.2054 < 5.17.3
5.17.2054 < 5.17.30

The first (or both first and second) version sub-number, however, is always treated as an integer value it actually equals to.

If you use this kind of versioning, you may change just a few lines in the example:

// replace this:
p1 = parseInt(v1parts[i], 10);
p2 = parseInt(v2parts[i], 10);
// with this:
p1 = i/* > 0 */ ? parseFloat('0.' + v1parts[i], 10) : parseInt(v1parts[i], 10);
p2 = i/* > 0 */ ? parseFloat('0.' + v2parts[i], 10) : parseInt(v2parts[i], 10);

So every sub-number except the first one will be compared as a float, so 09 and 1 will become 0.09 and 0.1 accordingly and compared properly this way. 2054 and 3 will become 0.2054 and 0.3.

The complete version then, is (credits to @mar10):

/** Compare two dotted version strings (like '10.2.3').
 * @returns {Integer} 0: v1 == v2, -1: v1 < v2, 1: v1 > v2
 */
function versionCompare(v1, v2) {
    var v1parts = ("" + v1).split("."),
        v2parts = ("" + v2).split("."),
        minLength = Math.min(v1parts.length, v2parts.length),
        p1, p2, i;
    // Compare tuple pair-by-pair. 
    for(i = 0; i < minLength; i++) {
        // Convert to integer if possible, because "8" > "10".
        p1 = i/* > 0 */ ? parseFloat('0.' + v1parts[i], 10) : parseInt(v1parts[i], 10);;
        p2 = i/* > 0 */ ? parseFloat('0.' + v2parts[i], 10) : parseInt(v2parts[i], 10);
        if (isNaN(p1)){ p1 = v1parts[i]; } 
        if (isNaN(p2)){ p2 = v2parts[i]; } 
        if (p1 == p2) {
            continue;
        }else if (p1 > p2) {
            return 1;
        }else if (p1 < p2) {
            return -1;
        }
        // one operand is NaN
        return NaN;
    }
    // The longer tuple is always considered 'greater'
    if (v1parts.length === v2parts.length) {
        return 0;
    }
    return (v1parts.length < v2parts.length) ? -1 : 1;
}

P.S. It is slower, but also possible to think on re-using the same comparing function operating the fact that the string is actually the array of characters:

 function cmp_ver(arr1, arr2) {
     // fill the tail of the array with smaller length with zeroes, to make both array have the same length
     while (min_arr.length < max_arr.length) {
         min_arr[min_arr.lentgh] = '0';
     }
     // compare every element in arr1 with corresponding element from arr2, 
     // but pass them into the same function, so string '2054' will act as
     // ['2','0','5','4'] and string '19', in this case, will become ['1', '9', '0', '0']
     for (i: 0 -> max_length) {
         var res = cmp_ver(arr1[i], arr2[i]);
         if (res !== 0) return res;
     }
 }

Solution 34 - Javascript

This isn't a quite solution for the question was asked, but it's very similiar.

This sort function is for semantic versions, it handles resolved version, so it doesn't work with wildcards like x or *.

It works with versions where this regular expression matches: /\d+\.\d+\.\d+.*$/. It's very similar to this answer except that it works also with versions like 1.2.3-dev. In comparison with the other answer: I removed some checks that I don't need, but my solution can be combined with the other one.

semVerSort = function(v1, v2) {
  var v1Array = v1.split('.');
  var v2Array = v2.split('.');
  for (var i=0; i<v1Array.length; ++i) {
    var a = v1Array[i];
    var b = v2Array[i];
    var aInt = parseInt(a, 10);
    var bInt = parseInt(b, 10);
    if (aInt === bInt) {
      var aLex = a.substr((""+aInt).length);
      var bLex = b.substr((""+bInt).length);
      if (aLex === '' && bLex !== '') return 1;
      if (aLex !== '' && bLex === '') return -1;
      if (aLex !== '' && bLex !== '') return aLex > bLex ? 1 : -1;
      continue;
    } else if (aInt > bInt) {
      return 1;
    } else {
      return -1;
    }
  }
  return 0;
}

The merged solution is that:

function versionCompare(v1, v2, options) {
    var zeroExtend = options && options.zeroExtend,
        v1parts = v1.split('.'),
        v2parts = v2.split('.');

    if (zeroExtend) {
        while (v1parts.length < v2parts.length) v1parts.push("0");
        while (v2parts.length < v1parts.length) v2parts.push("0");
    }

    for (var i = 0; i < v1parts.length; ++i) {
        if (v2parts.length == i) {
            return 1;
        }
        var v1Int = parseInt(v1parts[i], 10);
        var v2Int = parseInt(v2parts[i], 10);
        if (v1Int == v2Int) {
            var v1Lex = v1parts[i].substr((""+v1Int).length);
            var v2Lex = v2parts[i].substr((""+v2Int).length);
            if (v1Lex === '' && v2Lex !== '') return 1;
            if (v1Lex !== '' && v2Lex === '') return -1;
            if (v1Lex !== '' && v2Lex !== '') return v1Lex > v2Lex ? 1 : -1;
            continue;
        }
        else if (v1Int > v2Int) {
            return 1;
        }
        else {
            return -1;
        }
    }

    if (v1parts.length != v2parts.length) {
        return -1;
    }

    return 0;
}

Solution 35 - Javascript

I had the same problem of version comparison, but with versions possibly containing anything (ie: separators that were not dots, extensions like rc1, rc2...).

I used this, which basically split the version strings into numbers and non-numbers, and tries to compare accordingly to the type.

function versionCompare(a,b) {
  av = a.match(/([0-9]+|[^0-9]+)/g)
  bv = b.match(/([0-9]+|[^0-9]+)/g)
  for (;;) {
    ia = av.shift();
    ib = bv.shift();
    if ( (typeof ia === 'undefined') && (typeof ib === 'undefined') ) { return 0; }
    if (typeof ia === 'undefined') { ia = '' }
    if (typeof ib === 'undefined') { ib = '' }
    
    ian = parseInt(ia);
    ibn = parseInt(ib);
    if ( isNaN(ian) || isNaN(ibn) ) {
      // non-numeric comparison
      if (ia < ib) { return -1;}
      if (ia > ib) { return 1;}
    } else {
      if (ian < ibn) { return -1;}
      if (ian > ibn) { return 1;}
    }
  }
}

There are some assumptions here for some cases, for example : "1.01" === "1.1", or "1.8" < "1.71". It fails to manage "1.0.0-rc.1" < "1.0.0", as specified by Semantic versionning 2.0.0

Solution 36 - Javascript

Preprocessing the versions prior to the sort means parseInt isn't called multiple times unnecessarily. Using Array#map similar to Michael Deal's suggestion, here's a sort I use to find the newest version of a standard 3 part semver:

var semvers = ["0.1.0", "1.0.0", "1.1.0", "1.0.5"];

var versions = semvers.map(function(semver) {
    return semver.split(".").map(function(part) {
        return parseInt(part);
    });
});

versions.sort(function(a, b) {
    if (a[0] < b[0]) return 1;
    else if (a[0] > b[0]) return -1;
    else if (a[1] < b[1]) return 1;
    else if (a[1] > b[1]) return -1;
    else if (a[2] < b[2]) return 1;
    else if (a[2] > b[2]) return -1;
    return 0;
});

var newest = versions[0].join(".");
console.log(newest); // "1.1.0"

Solution 37 - Javascript

One more implementation I believe worth sharing as it's short, simple and yet powerful. Please note that it uses digit comparison only. Generally it checks if version2 is later than version1 and returns true if it's the case. Suppose you have version1: 1.1.1 and version2: 1.1.2. It goes through each part of the two versions adding their parts as follows: (1 + 0.1) then (1.1 + 0.01) for version1 and (1 + 0.1) then (1.1 + 0.02) for version2.

function compareVersions(version1, version2) {
    
    version1 = version1.split('.');
    version2 = version2.split('.');
    
   	var maxSubVersionLength = String(Math.max.apply(undefined, version1.concat(version2))).length;
        
	var reduce = function(prev, current, index) {
                        
        return parseFloat(prev) + parseFloat('0.' + Array(index + (maxSubVersionLength - String(current).length)).join('0') + current);
    };

    return version1.reduce(reduce) < version2.reduce(reduce);
}

If you want to find the latest version out of list of versions then this might be useful:

function findLatestVersion(versions) {

    if (!(versions instanceof Array)) {
        versions = Array.prototype.slice.apply(arguments, [0]);
    }
    
    versions = versions.map(function(version) { return version.split('.'); });
    
    var maxSubVersionLength = String(Math.max.apply(undefined, Array.prototype.concat.apply([], versions))).length;
        
    var reduce = function(prev, current, index) {

        return parseFloat(prev) + parseFloat('0.' + Array(index + (maxSubVersionLength - String(current).length)).join('0') + current);
    };
    
    var sums = [];

    for (var i = 0; i < versions.length; i++) {
        sums.push(parseFloat(versions[i].reduce(reduce)));
    }

    return versions[sums.indexOf(Math.max.apply(undefined, sums))].join('.');
}

console.log(findLatestVersion('0.1000000.1', '2.0.0.10', '1.6.10', '1.4.3', '2', '2.0.0.1')); // 2.0.0.10
console.log(findLatestVersion(['0.1000000.1', '2.0.0.10', '1.6.10', '1.4.3', '2', '2.0.0.1'])); // 2.0.0.10

Solution 38 - Javascript

Here's another way to do it with recursive algorithm.

This code just uses Array.shift and recursive, which means that it can run in IE 6+. If you have any doubts, you can visit my GitHub

(function(root, factory) {
  if (typeof exports === 'object') {
    return module.exports = factory();
  } else if (typeof define === 'function' && define.amd) {
    return define(factory);
  } else {
    return root.compareVer = factory();
  }
})(this, function() {
  'use strict';
  var _compareVer;
  _compareVer = function(newVer, oldVer) {
    var VER_RE, compareNum, isTrue, maxLen, newArr, newLen, newMatch, oldArr, oldLen, oldMatch, zerofill;
    VER_RE = /(\d+\.){1,9}\d+/;
    if (arguments.length !== 2) {
      return -100;
    }
    if (typeof newVer !== 'string') {
      return -2;
    }
    if (typeof oldVer !== 'string') {
      return -3;
    }
    newMatch = newVer.match(VER_RE);
    if (!newMatch || newMatch[0] !== newVer) {
      return -4;
    }
    oldMatch = oldVer.match(VER_RE);
    if (!oldMatch || oldMatch[0] !== oldVer) {
      return -5;
    }
    newVer = newVer.replace(/^0/, '');
    oldVer = oldVer.replace(/^0/, '');
    if (newVer === oldVer) {
      return 0;
    } else {
      newArr = newVer.split('.');
      oldArr = oldVer.split('.');
      newLen = newArr.length;
      oldLen = oldArr.length;
      maxLen = Math.max(newLen, oldLen);
      zerofill = function() {
        newArr.length < maxLen && newArr.push('0');
        oldArr.length < maxLen && oldArr.push('0');
        return newArr.length !== oldArr.length && zerofill();
      };
      newLen !== oldLen && zerofill();
      if (newArr.toString() === oldArr.toString()) {
        if (newLen > oldLen) {
          return 1;
        } else {
          return -1;
        }
      } else {
        isTrue = -1;
        compareNum = function() {
          var _new, _old;
          _new = ~~newArr.shift();
          _old = ~~oldArr.shift();
          _new > _old && (isTrue = 1);
          return _new === _old && newArr.length > 0 && compareNum();
        };
        compareNum();
        return isTrue;
      }
    }
  };
  return _compareVer;
});

Well, I hope this codes help someone.

Here's the testing.

console.log(compareVer("0.0.2","0.0.1"));//1
console.log(compareVer("0.0.10","0.0.1")); //1
console.log(compareVer("0.0.10","0.0.2")); //1
console.log(compareVer("0.9.0","0.9")); //1
console.log(compareVer("0.10.0","0.9.0")); //1
console.log(compareVer("1.7", "1.07")); //1
console.log(compareVer("1.0.07", "1.0.007")); //1

console.log(compareVer("0.3","0.3")); //0
console.log(compareVer("0.0.3","0.0.3")); //0
console.log(compareVer("0.0.3.0","0.0.3.0")); //0
console.log(compareVer("00.3","0.3")); //0
console.log(compareVer("00.3","00.3")); //0
console.log(compareVer("01.0.3","1.0.3")); //0
console.log(compareVer("1.0.3","01.0.3")); //0

console.log(compareVer("0.2.0","1.0.0")); //-1
console.log(compareVer('0.0.2.2.0',"0.0.2.3")); //-1
console.log(compareVer('0.0.2.0',"0.0.2")); //-1
console.log(compareVer('0.0.2',"0.0.2.0")); //-1
console.log(compareVer("1.07", "1.7")); //-1
console.log(compareVer("1.0.007", "1.0.07")); //-1

console.log(compareVer()); //-100
console.log(compareVer("0.0.2")); //-100
console.log(compareVer("0.0.2","0.0.2","0.0.2")); //-100
console.log(compareVer(1212,"0.0.2")); //-2
console.log(compareVer("0.0.2",1212)); //-3
console.log(compareVer('1.abc.2',"1.0.2")); //-4
console.log(compareVer('1.0.2',"1.abc.2")); //-5

Solution 39 - Javascript

I find a simplest way to compare them, don't sure if it's what you want. when I run below code in console, it make sense, and using sort() method, I could get the sorted array of versions string. it's based on the alphabetical order.

"1.0" < "1.0.1" //true
var arr = ["1.0.1", "1.0", "3.2.0", "1.3"]
arr.sort();     //["1.0", "1.0.1", "1.3", "3.2.0"]

Solution 40 - Javascript

Here's a version that orders version strings without allocating any sub-strings or arrays. Being that it allocates fewer objects, there's less work for the GC to do.

There is one pair of allocations (to allow reuse of the getVersionPart method), but you could expand that to avoid allocations altogether if you were very performance sensitive.

const compareVersionStrings : (a: string, b: string) => number = (a, b) =>
{
    var ia = {s:a,i:0}, ib = {s:b,i:0};
    while (true)
    {
        var na = getVersionPart(ia), nb = getVersionPart(ib);

        if (na === null && nb === null)
            return 0;
        if (na === null)
            return -1;
        if (nb === null)
            return 1;
        if (na > nb)
            return 1;
        if (na < nb)
            return -1;
    }
};

const zeroCharCode = '0'.charCodeAt(0);

const getVersionPart = (a : {s:string, i:number}) =>
{
    if (a.i >= a.s.length)
        return null;

    var n = 0;
    while (a.i < a.s.length)
    {
        if (a.s[a.i] === '.')
        {
            a.i++;
            break;
        }

        n *= 10;
        n += a.s.charCodeAt(a.i) - zeroCharCode;
        a.i++;
    }
    return n;
}

Solution 41 - Javascript

this is my solution. it has accepted on leetcode. I met the problem in my interview today. But i did not solve it at that time. I thought about it again. Adding zeros to make the two arrays' length equal. Then comparison.

var compareVersion = function(version1, version2) {
    let arr1 = version1.split('.').map(Number);
    let arr2 = version2.split('.').map(Number);
    let diff = 0;
    if (arr1.length > arr2.length){
        diff = arr1.length - arr2.length;
        while (diff > 0){
            arr2.push(0);
            diff--;
        } 
    }
    else if (arr1.length < arr2.length){
        diff = arr2.length - arr1.length;
        while (diff > 0){
            arr1.push(0);
            diff--;
        }
    }
   
    let i = 0;
    while (i < arr1.length){
        if (arr1[i] > arr2[i]){
           return 1;
       } else if (arr1[i] < arr2[i]){
           return -1;
       }
        i++;
    }
    return 0;
    
};

Solution 42 - Javascript

The function will return -1 if the version are equal, 0 if the first version is the latest and 1 to indicate the second version is the latest.

let v1 = '12.0.1.0'
let v2 = '12.0.1'

let temp1 = v1.split('.');
let temp2 = v2.split('.');

console.log(compareVersion(temp1, temp2))


function compareVersion(version1, version2) {
	let flag = false;
	var compareResult;
	let maxLength = Math.max(version1.length, version2.length); 
	let minLength = Math.min(version1.length, version2.length);

	for (let i = 0; i < maxLength; ++i ) {
		let result = version1[i] - version2[i];
		if (result > 0) {
			flag = true;
			compareResult = 0;
			break;
		}
		else if (result < 0) {
			flag = true;
			compareResult = 1;
			break;
		}
		
		if (i === minLength) {
			if (version1.length > version1.length) {
				compareResult = version1[version1.length-1] > 0 ? '0' : '-1'
			}  else  {
				compareResult = version1[version2.length-1] > 0 ? '1' : '-1'
			}
			break;
		}
	}
	if (flag === false) {
		compareResult = -1;
	}
	return compareResult;
}

Solution 43 - Javascript

I didn't love any of the solutions so I rewrote it for my coding preferences. Notice the last four checks come out slightly different than the accepted answer. Works for me.

function v_check(version_a, version_b) {
	// compares version_a as it relates to version_b
	// a = b => "same"
	// a > b => "larger"
	// a < b => "smaller"
	// NaN   => "invalid"
	
	const arr_a = version_a.split('.');
	const arr_b = version_b.split('.');
	
	let result = "same"; // initialize to same // loop tries to disprove
	
	// loop through a and check each number against the same position in b
	for (let i = 0; i < arr_a.length; i++) {
		let a = arr_a[i];
		let b = arr_b[i];
		
		// same up to this point so if a is not there, a is smaller
		if (typeof a === 'undefined') {
			result = "smaller";
			break;
		
		// same up to this point so if b is not there, a is larger
		} else if (typeof b === 'undefined') {
			result = "larger";
			break;
			
		// otherwise, compare the two numbers
		} else {
		
			// non-positive numbers are invalid
			if (a >= 0 && b >= 0) {
			
				if (a < b) {
					result = "smaller";
					break;
				}
				else if (a > b) {
					result = "larger";
					break;
				}
				
			} else {
				result = "invalid";
				break;
			}
		}
	}
	
	// account for the case where the loop ended but there was still a position in b to evaluate
	if (result == "same" && arr_b.length > arr_a.length) result = "smaller";
	
	return result;
}


console.log(v_check("1.7.1", "1.7.10"));  // smaller
console.log(v_check("1.6.1", "1.7.10"));  // smaller
console.log(v_check("1.6.20", "1.7.10")); // smaller
console.log(v_check("1.7.1", "1.7.10"));  // smaller
console.log(v_check("1.7", "1.7.0"));     // smaller
console.log(v_check("1.7", "1.8.0"));     // smaller

console.log(v_check("1.7.10", "1.7.1"));  // larger
console.log(v_check("1.7.10", "1.6.1"));  // larger
console.log(v_check("1.7.10", "1.6.20")); // larger
console.log(v_check("1.7.0", "1.7"));     // larger
console.log(v_check("1.8.0", "1.7"));     // larger

console.log(v_check("1.7.10", "1.7.10")); // same
console.log(v_check("1.7", "1.7"));       // same

console.log(v_check("1.7", "1..7")); // larger
console.log(v_check("1.7", "Bad"));  // invalid
console.log(v_check("1..7", "1.7")); // smaller
console.log(v_check("Bad", "1.7"));  // invalid

Solution 44 - Javascript

I had to compare the version of my extension, but did not find here working solution, almost all the proposed options break when comparing 1.89 > 1.9 or 1.24.1 == 1.240.1

here I started from the fact that zeros go down only in the last record 1.1 == 1.10 and 1.10.1 > 1.1.1

compare_version = (new_version, old_version) => {
    new_version = new_version.split('.');
    old_version = old_version.split('.');
    for(let i = 0, m = Math.max(new_version.length, old_version.length); i<m; i++){
        //compare text
        let new_part = (i<m-1?'':'.') + (new_version[i] || 0)
        ,   old_part = (i<m-1?'':'.') + (old_version[i] || 0);
        //compare number (I don’t know what better)
      //let new_part = +((i<m-1?0:'.') + new_version[i]) || 0
      //,   old_part = +((i<m-1?0:'.') + old_version[i]) || 0;
        //console.log(new_part, old_part);
        if(old_part > new_part)return 0;    //change to -1 for sort the array
        if(new_part > old_part)return 1
    }
    return 0
};
compare_version('1.0.240.1','1.0.240.1');   //0 
compare_version('1.0.24.1','1.0.240.1');    //0
compare_version('1.0.240.89','1.0.240.9');  //0
compare_version('1.0.24.1','1.0.24');       //1

I'm not a big specialist, but I built simple code to compare 2 versions, change the first return to -1 to sort the array of versions

['1.0.240', '1.0.24', '1.0.240.9', '1.0.240.89'].sort(compare_version)
//results ["1.0.24", "1.0.240", "1.0.240.89", "1.0.240.9"]

and short version for compare full string

c=e=>e.split('.').map((e,i,a)=>e[i<a.length-1?'padStart':'padEnd'](5)).join('');

//results "    1    0  2409    " > "    1    0  24089   "

c('1.0.240.9')>c('1.0.240.89')              //true

If you have comments or improvements, do not hesitate to suggest

Solution 45 - Javascript

I have created this solution, I hope you find it useful:

https://runkit.com/ecancino/5f3c6c59593d23001485992e


const quantify = max => (n, i) => n * (+max.slice(0, max.length - i))

const add = (a, b) => a + b

const calc = s => s.
    split('.').
    map(quantify('1000000')).
    reduce(add, 0)

const sortVersions = unsortedVersions => unsortedVersions
    .map(version => ({ version, order: calc(version) }))
    .sort((a, b) => a.order - b.order)
    .reverse()
    .map(o => o.version)

Solution 46 - Javascript

Here is my solution works for any level of depth for either version.

Auto deal with number+dot issue. If not so function exists and console log would give undefined instead of truthy false or true.

Auto deal with trailing zero issue.

Auto relay exists where ever possible.

Auto backward compatible on old browsers.

function checkVersion (vv,vvv){
if(!(/^[0-9.]*$/.test(vv) && /^[0-9.]*$/.test(vvv))) return;
va = vv.toString().split('.');
vb = vvv.toString().split('.');
length = Math.max(va.length, vb.length);
for (i = 0; i < length; i++) {

if ((va[i]|| 0) < (vb[i]|| 0)  ) {return false; } 
  }
  return true;}
  
  console.log(checkVersion('20.0.0.1' , '20.0.0.2'));
  console.log(checkVersion(20.0 , '20.0.0.2'));
  console.log(checkVersion('20.0.0.0.0' , 20));
  console.log(checkVersion('20.0.0.0.1' , 20));
  console.log(checkVersion('20.0.0-0.1' , 20));

Solution 47 - Javascript

May I also advertise for the lightweight library I made to solve this problem?

https://github.com/pearnaly/semantic-version

You can use it both Object-Oriented and function-oriented. It is available as npm-package and ready-to-use bundle files.

Solution 48 - Javascript

const compareAppVersions = (firstVersion, secondVersion) => {
  const firstVersionArray = firstVersion.split(".").map(Number);
  const secondVersionArray = secondVersion.split(".").map(Number);
  const loopLength = Math.max(
    firstVersionArray.length,
    secondVersionArray.length
  );
  for (let i = 0; i < loopLength; ++i) {
    const a = firstVersionArray[i] || 0;
    const b = secondVersionArray[i] || 0;
    if (a !== b) {
      return a > b ? 1 : -1;
    }
  }
  return 0;
};

Solution 49 - Javascript

function compare(versionA: string | undefined, versionB: string | undefined, operator: string = '>') {
    if (versionA === undefined || versionB === undefined) {
        return false
    }
    const listA = versionA.split('.')
    const listB = versionB.split('.')
    let a = []
    let b = []
    for (let i = 0; i < listA.length; i++) {
        a.push(parseInt(listA[i].replace(/\D/g, ''), 10))
        b.push(parseInt(listB[i].replace(/\D/g, ''), 10))
    }

    for (let i = 0; i < listA.length; i++) {
        switch (operator) {
            case '>':
            case '>=':
                if (a[i] === b[i]) {
                    continue
                }
                if (a[i] > b[i]) {
                    return true
                }
                if (a[i] < b[i]) {
                    return false
                }
                break
            case '<':
            case '<=':
                if (a[i] === b[i]) {
                    continue
                }
                if (a[i] > b[i]) {
                    return false
                }
                if (a[i] < b[i]) {
                    return true
                }
                break
            case '=':
               if (a[i] > b[i]) {
                   return false
               }
               if (a[i] < b[i]) {
                   return false
               }
               break
        }
    }
    switch (operator) {
        case '>':
            return false
        case '<':
            return false
        case '=':
        case '>=':
        case '<=':
            return true
    }
}

Solution 50 - Javascript

Base on @Idan's awesome answer, the following function semverCompare passed most cases of Semantic Versioning 2.0.0, see this gist for more.

function semverCompare(a, b) {
    if (a.startsWith(b + "-")) return -1
    if (b.startsWith(a + "-")) return 1
    return a.localeCompare(b, undefined, { numeric: true, sensitivity: "case", caseFirst: "upper" })
}

It returns:

  • -1: a < b
  • 0: a == b
  • 1: a > b

Solution 51 - Javascript

You can loop through every period-delimited character and convert it to an int:

var parts = versionString.split('.');

for (var i = 0; i < parts.length; i++) {
  var value = parseInt(parts[i]);
  // do stuffs here.. perhaps build a numeric version variable?
}

Solution 52 - Javascript

Here's a fun way to do it OO:

    function versionString(str) {
    var parts = str.split('.');
    this.product = parts.length > 0 ? parts[0] * 1 : 0;
    this.major = parts.length > 1 ? parts[1] * 1 : 0;
    this.minor = parts.length > 2 ? parts[2] * 1 : 0;
    this.build = parts.length > 3 ? parts[3] * 1 : 0;

    this.compareTo = function(vStr){
        vStr = this._isVersionString(vStr) ? vStr : new versionString(vStr);
        return this.compare(this, vStr);
    };

    this.toString = function(){
        return this.product + "." + this.major + "." + this.minor + "." + this.build;
    }

    this.compare = function (str1, str2) {
        var vs1 = this._isVersionString(str1) ? str1 : new versionString(str1);
        var vs2 = this._isVersionString(str2) ? str2 : new versionString(str2);

        if (this._compareNumbers(vs1.product, vs2.product) == 0) {
            if (this._compareNumbers(vs1.major, vs2.major) == 0) {
                if (this._compareNumbers(vs1.minor, vs2.minor) == 0) {
                    return this._compareNumbers(vs1.build, vs2.build);
                } else {
                    return this._compareNumbers(vs1.minor, vs2.minor);
                }
            } else {
                return this._compareNumbers(vs1.major, vs2.major);
            }
        } else {
            return this._compareNumbers(vs1.product, vs2.product);
        }
    };

    this._isVersionString = function (str) {
        return str !== undefined && str.build !== undefined;
    };

    this._compareNumbers = function (n1, n2) {
        if (n1 > n2) {
            return 1;
        } else if (n1 < n2) {
            return -1;
        } else {
            return 0;
        }
    };
}

And some tests:

var v1 = new versionString("1.0");
var v2 = new versionString("1.0.1");
var v3 = new versionString("2.0");
var v4 = new versionString("2.0.0.1");
var v5 = new versionString("2.0.1");


alert(v1.compareTo("1.4.2"));
alert(v3.compareTo(v1));
alert(v5.compareTo(v4));
alert(v4.compareTo(v5));
alert(v5.compareTo(v5));

Solution 53 - Javascript

It really depends on the logic behind your versioning system. What does each number represent, and how it is used.

Is each subversion is a numeration for designating development stage? 0 for alpha 1 for beta 2 for release candidate 3 for (final) release

Is it a build version? Are you applying incremental updates?

Once you know how the versioning system works, creating the algorithm becomes easy.

If you don't allow numbers greater than 9 in each subversion, eliminating all the decimals but the first will allow you to do a straight comparison.

If you do allow numbers greater than 9 in any of subversions, there are several ways to compare them. The most obvious is to split the string by the decimals and compare each column.

But without knowing how the versioning system works, implementing a process like the ones above can get harry when version 1.0.2a is released.

Solution 54 - Javascript

function versionCompare(version1, version2){
				var a = version1.split('.');
		        var b = version2.split('.');
		        for (var i = 0; i < a.length; ++i) {
		            a[i] = Number(a[i]);
		        }
		        for (var i = 0; i < b.length; ++i) {
		            b[i] = Number(b[i]);
		        }
		        var length=a.length;
		        
		        for(j=0; j<length; j++){
		        	if(typeof b[j]=='undefined')b[j]=0;
		        	if (a[j] > b[j]) return true;
		        	else if(a[j] < b[j])return false;
		        	if(j==length-1 && a[j] >= b[j])return true;
		        }		      

		        return false;
			},

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTattatView Question on Stackoverflow
Solution 1 - JavascriptJonView Answer on Stackoverflow
Solution 2 - JavascriptMohammed AkdimView Answer on Stackoverflow
Solution 3 - JavascriptJoeView Answer on Stackoverflow
Solution 4 - JavascriptLeJaredView Answer on Stackoverflow
Solution 5 - JavascriptIdanView Answer on Stackoverflow
Solution 6 - JavascriptArthur RonconiView Answer on Stackoverflow
Solution 7 - Javascriptuser123444555621View Answer on Stackoverflow
Solution 8 - JavascriptViktorView Answer on Stackoverflow
Solution 9 - JavascriptvanowmView Answer on Stackoverflow
Solution 10 - JavascriptAwesome DevView Answer on Stackoverflow
Solution 11 - Javascriptpery mimonView Answer on Stackoverflow
Solution 12 - JavascriptNoxinView Answer on Stackoverflow
Solution 13 - JavascriptkanoView Answer on Stackoverflow
Solution 14 - JavascriptpowtacView Answer on Stackoverflow
Solution 15 - JavascriptAllyView Answer on Stackoverflow
Solution 16 - JavascriptNina ScholzView Answer on Stackoverflow
Solution 17 - JavascriptDanny '365CSI' EngelmanView Answer on Stackoverflow
Solution 18 - JavascriptGorvGoylView Answer on Stackoverflow
Solution 19 - JavascriptSid VishnoiView Answer on Stackoverflow
Solution 20 - JavascriptAnisView Answer on Stackoverflow
Solution 21 - JavascriptMarcView Answer on Stackoverflow
Solution 22 - JavascriptDyllan MView Answer on Stackoverflow
Solution 23 - JavascriptdreamLoView Answer on Stackoverflow
Solution 24 - JavascriptSascha GalleyView Answer on Stackoverflow
Solution 25 - JavascriptDavidView Answer on Stackoverflow
Solution 26 - Javascriptmar10View Answer on Stackoverflow
Solution 27 - JavascriptMichael DealView Answer on Stackoverflow
Solution 28 - JavascriptAdrian SView Answer on Stackoverflow
Solution 29 - JavascriptLOASView Answer on Stackoverflow
Solution 30 - JavascriptQuentin RossettiView Answer on Stackoverflow
Solution 31 - JavascriptWill SchulzView Answer on Stackoverflow
Solution 32 - JavascriptContraView Answer on Stackoverflow
Solution 33 - Javascriptshaman.sirView Answer on Stackoverflow
Solution 34 - JavascripttimaschewView Answer on Stackoverflow
Solution 35 - JavascriptUrielView Answer on Stackoverflow
Solution 36 - JavascripttheGeckoView Answer on Stackoverflow
Solution 37 - JavascriptChris CzoppView Answer on Stackoverflow
Solution 38 - JavascriptJ.GView Answer on Stackoverflow
Solution 39 - JavascriptinoutwhyView Answer on Stackoverflow
Solution 40 - JavascriptDrew NoakesView Answer on Stackoverflow
Solution 41 - Javascriptmetrical1View Answer on Stackoverflow
Solution 42 - JavascriptleoxView Answer on Stackoverflow
Solution 43 - JavascriptBrandon BlackwellView Answer on Stackoverflow
Solution 44 - JavascriptkillovvView Answer on Stackoverflow
Solution 45 - JavascriptEduardo CancinoView Answer on Stackoverflow
Solution 46 - JavascriptSyedView Answer on Stackoverflow
Solution 47 - JavascriptBillView Answer on Stackoverflow
Solution 48 - JavascriptEduard K.View Answer on Stackoverflow
Solution 49 - JavascriptHakan SaglamView Answer on Stackoverflow
Solution 50 - JavascriptMr. MíngView Answer on Stackoverflow
Solution 51 - JavascriptKonView Answer on Stackoverflow
Solution 52 - JavascriptBrianView Answer on Stackoverflow
Solution 53 - JavascriptUtilitronView Answer on Stackoverflow
Solution 54 - JavascriptSakisView Answer on Stackoverflow