Francisc Francisc - 5 months ago 14
Javascript Question

Check if an element is present in an array

The function I am using now to check this is the following:

function inArray(needle,haystack)
{
var count=haystack.length;
for(var i=0;i<count;i++)
{
if(haystack[i]===needle){return true;}
}
return false;
}


It works. What I'm looking for is whether there is a better way of doing this.

Answer

Code:

function isInArray(value, array) {
  return array.indexOf(value) > -1;
}

Execution:

isInArray(1, [1,2,3]); // true