RegEx version control this is my first time on this stack exchange :)

I created a little script to check for the latest version of specified API version available, but I am wondering if I am using the best way possible for checking regex and includes?

The var arr will be filled dynamically with version folders using fs.readdir, but for simplicity I wrote them in the array manually and the var pattern will come from req.params.v using nodejs express router middleware.

Just looking for an approval or if there is a better way, thank you!

var arr = ['v1.0.0', 'v5.2.4', 'v5.2.9', 'v5.20.4', 'v6.4.0'];
var pattern = 'v5.2';

const regex = /^v[0-9](\.[0-9]{1,2})?(\.[0-9])?$/;

if (regex.test(pattern) &amp;&amp; (arr.filter(s =&gt; s.includes(pattern)) != 0)) {

    if (pattern.match(/\./g) == null) {
        console.log('major version');
        console.log(pattern);
    } else if (pattern.match(/\./g).length == 1) {
        console.log('minor version');
        console.log(pattern);
        pattern = pattern + '.';
    } else {
        console.log('patch version');
        console.log(pattern);
    }
    const matches = arr.filter(s =&gt; s.includes(pattern));
    console.log(matches[matches.length - 1]);

} else {
    console.log('Specify correct API version!');
}


Thank you in advance!
Likely logic flaw

In the first conditional:


if (regex.test(pattern) &amp;&amp; (arr.filter(s =&gt; s.includes(pattern)) != 0)) {



Array.filter() "creates a new array"1 so the second conditional expression compares an array with zero. Those two should never be loosely equal so that conditional always evaluates to true. Perhaps you intended to check the length property of the array.

Improving efficiency

The code has repeated operations - e.g. arr.filter(s =&gt; s.includes(pattern)) appears twice, and then there are multiple calls to pattern.match(). The call to arr.filter() could be stored in a variable and then used whenever needed instead of re-filtering. 

Also, the regular expression stored in regex could be used with String.match() to get an array of matches. Because the regular expression has capturing groups, those capturing groups can be used instead of calling pattern.match(/\./g) multiple times to check for the number of dots. Instead, check if the array returned by String.match() isn't null and then if the 2nd and 3rd elements are undefined.

See a comparison in this jsPerf.

1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter