You are here: Home Tech Perform Containment test on arrays in Javascript

Perform Containment test on arrays in Javascript

by Reed O'Brien last modified Dec 19, 2010 02:05 AM
A prototype for performing containment tests in Javascript; the moral equivalent of __contains__ for sequences.

I was looking to see if there was an easy way to do membership tests on an array in JS. 


Given an array/list:

my_array = ['this', 'that', 1, 3]

I can perform a membership test like so:

>>> 'this' in my_array


Javascript, however, has no such function. I came across a nice prototype by a guy named Terence which I have reposted here incase blogger goes the way of delicious/wave/yougettheidea:


Array.prototype.Contains = function(mxd,strict) {
for(i in this) {
if(this[i] == mxd && !strict) return true;
else if(this[i] === mxd) return true;
return false;

You can use it as such:

> my_array.Contains(2)
> my_array.Contains("this")


Share this: