Francisc Francisc - 1 year ago 102
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 Source


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


isInArray(1, [1,2,3]); // true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download