Check if a value is in an array?

Hi,

I want to check if a value is in an array. How do I do it?

For example, I have an array of ten numbers, and I want to know if one of the numbers is 35. Is there an easier way than looping through it? I know PHP has a function for this.

Thanks!

There is a lazy way of doing this :wink:

Instead of

var rain = new Array();
rain[0] = 'dogs';
rain[1] = 'cats';

do

var rain = new Array();
rain['dogs'] = 1;
rain['cats'] = 1;

if(rain['cats'] && rain['dogs']) {
  //do something
}

Probably you can created a small global function isValueInArray (array. value) that returns null if the value is not found or the array position if the value is in the array (note that zero is a valid value since arrays in javascript starts from zero)

var vector = arguments[0];
var test_value = arguments[1];
for ( var i = 0 ; i < vector.length; i++ )
{
	if (vector[i] == test_value) return i;
}
return null;

and then you can use it like this:

var pippo = new Array (1,2,3,4,5);
var myposition = isValueInArray(pippo,3)
if (myposition != null)
{
  application.output ("Found in position " + myposition);
}
else
{
   application.output ("Not found");
}

Tip: Place this global function in a module and include it in all your applications… very handy… SERVOY ROCKS

JavaScript 1.6 has a few new methods for array. One of these is .indexOf(searchElement[, fromIndex]). It searches a value in an array and returns the position of the first occurence.

This is already enabled in Firefox 1.5 so you can give it a try.

I hope Servoy will adopt this version of JavaScript as soon as possible. It will avoid us a lot of headaches when using arrays.