Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Using regular expressions to search an array of numbers?

1. ## Using regular expressions to search an array of numbers?

Hi:
Lets say I have an array containing a set of numbers:

var possibleids=[2, 23, 4, 5, 8]

and I wish to scan through this array using regular expressions to see if one of them matches the number contained in another variable:

var myid=2

In other words:

if (myid==one of possibleids)
//do this

What would be the easiest way using regular expressions? I could easily do this using a for loop and "indexOf()", but I wish to be a little more elegant.

Thanks,

• Code:
```function in_array(arr,num)
{
return RegExp(",?"+num+",?").test(arr.valueOf());
}```
something like this. IMO loop approach is better.

Code:
```var
i=arr.length;
while(arr[--i]!=myid)
if(i<0)
break;
alert(i+' is the number you want');```

• Agreed. It think looping it still the better choice
Code:
```Array.prototype.inArray = function( val )
{
var i = this.length;
while( this[--i] != val )
if ( i == 0 ) return false;
return true;
}

Array.prototype.inArrayPattern = function( pattern )
{
var i = this.length;
while( !pattern.test( this[--i] ) )
if ( i == 0 ) return false;
return true;
}

Array.prototype.indexOf = function( val )
{
var i = this.length;
while( this[--i] != val )
if ( i == 0 ) return -1;
return i;
}

var pids=[2, 23, 4, 5, 8];
alert( [pids.inArray( 2 ), pids.inArray( 3 )].join( "\n" ) );
alert( [pids.inArrayPattern( /^3\$/ ), pids.inArrayPattern( /^23|4\$/ )].join( "\n" ) );
alert( [pids.indexOf( 4 ), pids.indexOf( 3 )].join( "\n" ) );```

• Oh, he wanted to see whether the value existed in the array at all, not it's index in the array...
Code:
```Array.prototype.contains=function(attr){
var
fnFind,
l=this.lenght;
switch(attr instanceof RegExp){
case true:
fnFind=function(val){
return attr.test(val);
}
break;
default:
fnFind=function(val){
return attr==val;
}
}
while(l-->0)
if(fnFind(this[l]))
return true;
return false;
}```
Code:
```Array.prototype.find=function(attr){
var
fnFind,
l=this.lenght;
switch(attr instanceof RegExp){
case true:
fnFind=function(val){
return attr.test(val);
}
break;
default:
fnFind=function(val){
return attr==val;
}
}
while(l-->0)
if(fnFind(this[l]))
break;
return l;
}```

• Thanks guys. The consensus seems to be just to just a for loop versus regular expressions. I guess there is something called "over elegance".

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•