Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine whether an array contains a value [duplicate]

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")); 
like image 857
Prasad Avatar asked Jul 25 '09 08:07

Prasad


People also ask

How do you check if there are duplicates in an array C++?

Using Set A simple and elegant solution is to construct a set from the array which retains only distinct elements. Then simply compare the set's size against the array's length. If both are not the same, then we can say that the array contains duplicates. This works in linear time and space.


1 Answers

jQuery has a utility function for this:

$.inArray(value, array) 

Returns index of value in array. Returns -1 if array does not contain value.

See also How do I check if an array includes an object in JavaScript?

like image 164
codeape Avatar answered Sep 22 '22 21:09

codeape