Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

What is the most concise and efficient way to find out if a JavaScript array contains an obj?

This is the only way I know to do it:

function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}

Is there a better and more concise way to accomplish this?

This is very closely related to Stack Overflow question Best way to find an item in a JavaScript Array? which addresses finding objects in an array using indexOf.

share|improve this question
25  
just tested: your way is actually the fastest for across browsers: jsperf.com/find-element-in-obj-vs-array/2 (apart from pre-saving a.length in a variable) while using indexOf (as in $.inArray) is much slower – Jörn Berkefeld Jul 2 '12 at 11:56
13  
many have replied that the Array#indexOf is your best choice here. But if you want something that can be correctly cast to Boolean, use this: ~[1,2,3].indexOf(4) will return 0 which will evaluate as false, whereas ~[1,2,3].indexOf(3) will return -3 which will evaluate as true. – lordvlad Oct 2 '13 at 7:59
3  
~ is not what you want to use to convert to a boolean, for that you need !. But in this case you want to check equality with -1, s o the function might endreturn [1,2,3].indexOf(3) === -1; ~ is a binary not, it will invert each bit of the value individually. – mcfedr Jun 20 '14 at 12:49
    
IE9 supports indexOf() as per w3schools.com/jsref/jsref_indexof_array.asp. If older browser better approach is to define prototype for indexOf() function as given in Array.indexOf in Internet Explorer – Lijo Jan 21 '15 at 21:42
6  
@Iordvlad [1,2,3].indexOf(4) will actually return -1. As @mcfedr pointed out, ~ is the bitwise-NOT operator, see ES5 11.4.8. Thing is, since the binary representation of -1 consists of only 1's, it's complement is 0, which evaluates as false. The complement of any other number will be non-zero, hence true. So, ~ works just fine and is often used in conjunction with indexOf. – mknecht Mar 14 '15 at 5:35

32 Answers 32

Literally:

(using Firefox v3.6, with for-in caveats as previously noted (HOWEVER the use below might endorse for-in for this very purpose! That is, enumerating array elements that ACTUALLY exist via a property index (HOWEVER, in particular, the array length property is NOT enumerated in the for-in property list!).).)

(Drag & drop the following complete URI's for immediate mode browser testing.)

javascript:

  function ObjInRA(ra){var has=false; for(i in ra){has=true; break;} return has;}

  function check(ra){
      return ['There is ',ObjInRA(ra)?'an':'NO',' object in [',ra,'].'].join('')
  }
  alert([
            check([{}]), check([]), check([,2,3]),
            check(['']), '\t (a null string)', check([,,,])
        ].join('\n'));

which displays:

There is an object in [[object Object]].
There is NO object in [].
There is an object in [,2,3].
There is an object in [].
     (a null string)
There is NO object in [,,].

Wrinkles: if looking for a "specific" object consider:

javascript: alert({}!={}); alert({}!=={});

and thus:

javascript:
  obj={prop:"value"}; ra1=[obj]; ra2=[{prop:"value"}];
  alert(ra1[0]==obj); alert(ra2[0]==obj);

Often ra2 is considered to "contain" obj as the literal entity {prop:"value"}.

A very coarse, rudimentary, naive (as in code needs qualification enhancing) solution:

javascript:
  obj={prop:"value"};   ra2=[{prop:"value"}];
  alert(
    ra2 . toSource() . indexOf( obj.toSource().match(/^.(.*).$/)[1] ) != -1 ?
      'found' :
      'missing' );

See ref: Searching for objects in JavaScript arrays.

share|improve this answer

Just another option

// usage: if ( ['a','b','c','d'].contains('b') ) { ... }
Array.prototype.contains = function(value){
    for (var key in this)
        if (this[key] === value) return true;
    return false;
}
share|improve this answer
1  
19  
Please don't use a for in loop to iterate over an array - for in loops should be used strictly for objects only. – Yi Jiang Jan 20 '11 at 16:33

protected by Josh Crozier Feb 14 '14 at 23:10

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.