Determine whether an array contains a value

I need to determine if a value exists in an array.

I am using the following function:

Array.prototype.contains = 
function(obj) 
{

  var i = this.length;

  while (i--) 
{

 
  if (this[i] == obj) 
{

 
 
  return true;

 
  
}
  
}
  return false;
 

The above function always returns false.

The array values and the function call is as below:

arrValues = [Sam,Great, Sample, High] alert(arrValues.contains(Sam));
 
Text Copied From stackoverflow.com
on : Sat, Jul 25, 2009 Views : 1291966

Accepted Answer

var contains = 
function(needle) 
{

  
// Per spec, the way to identify NaN is that it is not equal to itself
  var findNaN = needle !== needle;

  var indexOf;

   if(!findNaN &
&
 typeof Array.prototype.indexOf === '
function') 
{

 
  indexOf = Array.prototype.indexOf;

  
} else 
{

 
  indexOf = 
function(needle) 
{

 
 
  var i = -1, index = -1;

 
 
   for(i = 0;
 i < this.length;
 i++) 
{

 
 
 
  var item = this[i];

 
 
 
   if((findNaN &
&
 item !== item) || item === needle) 
{

 
 
 
 
  index = i;

 
 
 
 
  break;

 
 
 
  
}
 
 
  
}
 
 
   return index;

 
  
};

  
}
   return indexOf.call(this, needle) > -1;
 
};
 

You can use it like this:

var myArray = [0,1,2],
  needle = 1,
  index = contains.call(myArray, needle);
 
// true 

CodePen validation/usage

Text Copied From stackoverflow.com
on : Sat, Jul 25, 2009

Ask Question

If you want to ask question you must LogIn or SignUp
Login SignUp

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp