Check if an element or value exists in an array or not

This function will Check if an element or value exists in an array or not.
And return true if the passed value is found in the array. Returns false if it is not found in the array.

Array.prototype.inArray = function (value,caseSensitive)
// Returns true if the passed value is found in the
// array. Returns false if it is not.
{
var i;
for (i=0; i < this.length; i++) { // use === to check for Matches. ie., identical (===), if(caseSensitive){ //performs match even the string is case sensitive if (this[i].toLowerCase() == value.toLowerCase()) { return true; } }else{ if (this[i] == value) { return true; } } } return false; }; Note : If you don't want to perform case sensitive check, then set caseSensitve=true and call the function.

22 Replies to “Check if an element or value exists in an array or not”

  1. @Anton
    You guess wrong. this.length is a variable, not a method. It doesn’t count the size of an array. It’s just used to store the number of fields in array.

  2. @James Brown — I’m afraid that’s php 🙂 I was looking for something similar in JS, but it seems there’s no easy way doing this, xcept for the function Kumar posted. Too bad.

  3. I hadn’t tried, but what about this?

    String[] extensions = {“jpg”,”JPG”,”jpeg”,”JPEG”,”gif”,”GIF”,”png”,”PNG”};

    List tmp = Arrays.asList(extensions);

    if(tmp.contains(myKey)){
    yourCodeHere();
    }

  4. @Damien
    I’m afraid to say, What you have posted is not JavaScript code.
    Instead you can do like this

    
    function contains(a, obj) {
      var i = a.length;
      while (i--) {
        if (a[i] === obj) {
          return true;
        }
      }
      return false;
    }
    Else you can extend the array object as 
    Array.prototype.contains = function(obj) {
      var i = this.length;
      while (i--) {
        if (this[i] === obj) {
          return true;
        }
      }
      return false;
    }
    Then you can check the array like this
    var extensions = {?jpg?,?JPG?,?jpeg?,?JPEG?,?gif?,?GIF?,?png?,?PNG?};
    alert(extensions.contains("jpg")); // => true
    alert(extensions.contains('TXT')); // => false
    
  5. An easy way of doing this check (unless I’m missing something) is just to see if the element is undefined:

    var arr = new Array();
    arr["test"] = "I Exist!";
    if (arr["blah"] == undefined)
    alert("key blah doesn't exist");
    if (arr["test"]!=undefined)
    alert("key test is: '" + arr["test"] + "'");

  6. @Argoth:
    Writing
    arr[“test”] = “I Exist!”
    changes the nature of the variable arr from Array object to Object object. Your instruction is making “associative array” which is NOT really a simple array.

    @prasanth:
    But the blog here is about Array, not String. By the way, there’s no “list” object in JavaScript.

  7. I’m extremely new to Javascript, what I’m looking to do is effectively build a variable changing array which would determine and store a visitors IP address, so that upon a returned visit to the page a splash element would not appear to them. From what I’ve seen using a combination of the push() method and a simple array along with the ip = ‘‘; to determine the IP address I should be able to construct the array. However I am confused on how to read from the array and react according to whether or not the visitors IP address already exists in the Array. I know it’s a lot to ask but I would greatly appreciate any help that can be provided, if you are interested in helping me out please PLEASE email me as I may not stumble across this site again in my search for help on this issue. I can be reached at ethrock@gmail.com. Thanks again greatly in advance to anyone who is willing or able to help me out!

  8. The solution proposed by @prasanth works really well. Tested with any type of object.

    Example:

    var array = new Array("test","one more test","yes",15,22,new Date(79,5,24));
    if(array.indexOf("test")==-1) document.write("nope");
    else document.write("yeap");
    document.write("");
    if(array.indexOf("will not work")==-1) document.write("nope");
    else document.write("yeap");
    document.write("");
    if(array.indexOf("one more test")==-1) document.write("nope");
    else document.write("yeap");
    document.write("");
    if(array.indexOf(10)==-1) document.write("nope");
    else document.write("yeap");
    document.write("");
    if(array.indexOf(15)==-1) document.write("nope");
    else document.write("yeap");
    document.write("");
    if(array.indexOf(new Date(79,5,24))==-1) document.write("nope");
    else document.write("yeap");
    document.write("");
    if(array.indexOf(new Date(75,5,24))==-1) document.write("nope");
    else document.write("yeap");

  9. first of all, jquery sucks – if you are new to programming learn pure javascript before you go messing with libraries. second, this whole post is ridiculous, there is one correct way to determine whether or not an element exists in an array and that is what prasanth posted above:

    if (array.indexOf(‘find this’) != -1) {
    alert(‘exists’);
    }

    else if (array.indexOf(‘find this’) == -1) {
    alert(‘does not exist’);
    }

  10. I just had a friend come to me with this. People are still finding it, Kumar, please please update the post with a message pointing to https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

    I completely disagree with thomas on ‘jquery sucks learn bare js’ but he is right on the correct implementation

    The code in this post
    a) patches a native prototype (almost always bad)
    b) does so without checking for prexisting implementation
    c) has an inefficient for loop (recalculates length each time)
    d) repeatedly preforms the same calculation inside a loop
    e) recreates native functionality

    I realize this is old, but since people are still finding it they should know that this is a good way to fail you code review.
    If you need a more complex implementation study how underscore.js implements _.any (http://documentcloud.github.com/underscore/docs/underscore.html search for var any =) or just use underscore flat out

  11. @George Mauer
    As you mentioned, this code is having implementation issues like
    c) has an inefficient for loop (recalculates length each time)
    d) repeatedly preforms the same calculation inside a loop

    But, at the time of doing this, there is no indexOf function available.
    If you check the date of posting, (7 Yrs ago) you would know.

Leave a Reply to thomas Cancel reply

Your email address will not be published. Required fields are marked *