This question already has an answer here:
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"));
You can use _.indexOf method or if you don't want to include whole Underscore.js library in your app, you can have a look how they did it and extract necessary code.
Wow, there are a lot of great answers to this question.
I didn't see one that takes a
reduce
approach so I'll add it in:Here's a fiddle of it in action.
Using array .map function that executes a function for every value in an array seems cleanest to me.
Ref: Array.prototype.map()
This method can work well both for simple arrays and for arrays of objects where you need to see if a key/value exists in an array of objects.
It's almost always safer to use a library like lodash simply because of all the issues with cross-browser compatibilities and efficiency.
Efficiency because you can be guaranteed that at any given time, a hugely popular library like underscore will have the most efficient method of accomplishing a utility function like this.
If you're concerned about the bulk that's being added to your application by including the whole library, know that you can include functionality separately:
NOTICE: With older versions of lodash, this was
_.contains()
rather than_.includes()
.Another option would be to use
Array.some
(if available) in the following way:The anonymous function passed to
Array.some
will returntrue
if and only if there is an element in the array that is identical toobj
. Absent such an element, the function will not returntrue
for any of the elements of the array, soArray.some
will returnfalse
as well.The answer provided didn't work for me, but it gave me an idea:
It isn't perfect because items that are the same beyond the groupings could end up matching. Such as my example
When I call this function with the 'g' and 'h' fields containing 1 and 2 respectively, it still finds it because the resulting string from the join is: 1,1,2,2,3,3
Since it is doubtful in my situation that I will come across this type of situation, I'm using this. I thought I would share incase someone else couldn't make the chosen answer work either.