...

View Full Version : Using regular expressions to search an array of numbers?



WA
04-10-2003, 11:57 AM
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,

Weirdan
04-10-2003, 12:40 PM
function in_array(arr,num)
{
return RegExp(",?"+num+",?").test(arr.valueOf());
}


something like this. IMO loop approach is better.

liorean
04-10-2003, 03:43 PM
Regex aren't made for searching arrays. Loop through it instead.


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

beetle
04-10-2003, 03:50 PM
Agreed. It think looping it still the better choice
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" ) );

liorean
04-10-2003, 04:05 PM
Oh, he wanted to see whether the value existed in the array at all, not it's index in the array...
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;
}


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;
}

WA
04-10-2003, 10:20 PM
Thanks guys. The consensus seems to be just to just a for loop versus regular expressions. I guess there is something called "over elegance".



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum