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"));
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With