JavaScript Array Contains

Javascript objects are really nice, but sometimes they are missing some useful little functions/methods. The example above is with Arrays. It's really nice to know whether or not an item is contained within your array. Well you can write a function that takes the array and the item you're checking for, but it's much cleaner to add the contains( item ) method to the Array object.

Extending JavaScript Arrays

/**
 * Array.prototype.[method name] allows you to define/overwrite an objects method
 * needle is the item you are searching for
 * this is a special variable that refers to "this" instance of an Array.
 * returns true if needle is in the array, and false otherwise
 */
Array.prototype.contains = function ( needle ) {
   for (i in this) {
       if (this[i] == needle) return true;
   }
   return false;
}

Usage

// Now you can do things like:
var x = Array();
if (x.contains('foo')) {
   // do something special
}

Comments

  1. User Avatar
    V1
    Permalink to comment#

    I suggest making it more strict,

    if (this[i] == needle) return true;

    to:

    if (this[i] === needle) return true;

    for example, 1 is the same as true. Unless you do ===

  2. User Avatar
    Alex
    Permalink to comment#

    Thank you V1, you’re absolutely right. That should definitely be a ===.

  3. User Avatar
    James
    Permalink to comment#

    “i” should be declared locally (by using a var statement). Currently you’re setting it as a global variable. Also, you shouldn’t be using the “for(i in something)” construct for arrays. Instead use a traditional for or while loop; they’re much quicker.

  4. User Avatar
    Jhuni
    Permalink to comment#

    Here is how I would write it, coming in at a mere 83 kb minified:

    var contains = function( arr, value ) {
    
    	var i = 0, len = arr.length;
    
    	while( i < len && arr[i] != value ) {
    
    		i++;
    
    	}
    
    	return i != len;
    
    };
  5. User Avatar
    einstein
    Permalink to comment#

    Thank you, It really worked.

  6. User Avatar
    David Chambers
    Permalink to comment#

    Nicer still would be to write it like this:

    function contains(arr, value) {
        var i = arr.length;
        while (i--) {
            if (arr[i] === value) return true;
        }
        return false;
    }
  7. User Avatar
    John Doe
    Permalink to comment#

    /**
    * is_array
    *
    * @param mixed input
    * @return bol
    */

    function is_array(obj) {
    if (obj.constructor.toString().indexOf(‘Array’) == -1) {
    return false;
    }
    return true;
    }

    /**
    * contains
    *
    * @param mixed input
    * @param string value
    * @return bol
    */

    function contains(input, value) {
    if (!is_array(input)) {
    if (input.indexOf(value) != -1) {
    return true;
    }
    }
    else {
    var i = input.length;
    while (i–) {
    if (input[i] === value) {
    return true;
    }
    }
    }
    return false;
    }

  8. User Avatar
    watermelonbunny

    I rather to follow the lines of the String’s indexOf method.
    this functionality already exists in most browsers, so with a simple feature detection you can add it to non supporting browsers:

    if(!Array.indexOf){
     Array.prototype.indexOf = function(obj){
      for(var i=0;i<this.length;i++){
       if(this[i]==obj)
        return i;
      }
      return -1;
     }
    }
    

    obviously this does not return a boolean (if…!=-1) but you may want to know the first location of an object in an array so this comes in more handy, if you’re already there, you know..
    You can modify it to go backwards on the array, on large arrays going backwards is usually quicker (for some reason), but then you’ll get the last place an object will appear in the array

    var i = this.length;
    while(i--){
    ...
    }
    
  9. User Avatar
    black
    Permalink to comment#

    why not using the native indexOf()-method?

    function contains(arr, v) {
      return arr.indexOf(v) > -1;
    }
    
  10. User Avatar
    roxxypoxxy
    Permalink to comment#

    +1 for @black.
    arr.indexOf(v) > -1
    looks short and sweet.

  11. User Avatar
    Tim
    Permalink to comment#

    indexOf() is IE9+, boys.

    • User Avatar
      MarkG

      The thing is, anyone using anything that does not support HTML5 is an out of date browser (and yes I am aware that Mozilla are dragging its knuckles on this one) and in real terms, while it is nice to support these old browsers, the actual usage of them is declining to levels where support in terms of cost, benefits, time and effort in maintaining that code outweighs the perceived benefits for a very small browser user group.

      I would settle for this as a method covering most bases, simply stringify then test.

      Array.prototype.inArray = function( needle ){
          return Array(this).join(",").indexOf(needle) >-1;
      }
      

      … and likely drawing criticism with the usual, yes it has no checks, you can’t nanny people, if people misuse a function or code, thats their look out…

      If you want to make it more robust, try going along this path… :D

      Array.prototype.inArray = function( needle ){
          try{
              return Array(this).join(",").indexOf(needle) >-1;
          }catch(e){
              // Oooo, an error!
              if( window.console) console.log("Error : "+e)
          }
      }
      

      Adding a try & catch means that you will control errors, therefore some level of checking is happening although what it does in control is up to you!

      Use,

      var x = haystack.inArray(needle,3);
      var x = ["Cheese","Onion","Pickle","Ham"].inArray("Bread");
      

      As you would expect, false is the result, “Bread” does not appear in the list, therefore the logical response is false.

  12. User Avatar
    Cristian
    Permalink to comment#

    So usefull!! really thanks bro! nice tip

  13. User Avatar
    papiro
    Permalink to comment#
    Array.prototype.contains = function(needle){
      return RegExp('^'+needle+'$').test(this)
    }
    

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

Submit a Comment

icon-closeicon-emailicon-linkicon-menuicon-searchicon-tag