SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Wizard Wolf_22's Avatar
    Join Date
    Jul 2005
    Posts
    1,700
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Best way to find a value in array?

    Let's say I have the following array full of strings:

    Code:
    res = new Array("bob", "tom", "jerry", "sam", "carl", "james", "jim", "joe");
    ...and I have a a variable...

    Code:
    var s = "sam";
    What's the best way to compare the variable against the array to see if the variable is in the array? Is there an easy and efficient way to do this?

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    indexOf is perferct, but may not be available.
    Code:
    Array.prototype.indexOf= Array.prototype.indexOf || 
    function(what, index){
    	index= index || 0;
    	var L= this.length;
    	while(index< L){
    		if(this[index]=== what) return index;
    		++index;
    	}
    	return -1;
    }
    alert('res'.indexAt('sam')) // returns the index or -1
    alert('res'.indexAt('sam')!=-1) // true if 'sam' is in res, else false

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,526
    Mentioned
    83 Post(s)
    Tagged
    3 Thread(s)
    Have a look at https://developer.mozilla.org/En/Cor.../Array/IndexOf

    Code javascript:
    var res = new Array("bob", "tom", "jerry", "sam", "carl", "james", "jim", "joe");
    var index = res.indexOf('sam'); // 3

    There is also compatibility code at the above link for people not using modern web browsers (including Internet Explorer).

    Code javascript:
    if (!Array.prototype.indexOf)
    {
      Array.prototype.indexOf = function(elt /*, from*/)
      {
        var len = this.length >>> 0;
     
        var from = Number(arguments[1]) || 0;
        from = (from < 0)
             ? Math.ceil(from)
             : Math.floor(from);
        if (from < 0)
          from += len;
     
        for (; from < len; from++)
        {
          if (from in this &&
              this[from] === elt)
            return from;
        }
        return -1;
      };
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  4. #4
    SitePoint Wizard Wolf_22's Avatar
    Join Date
    Jul 2005
    Posts
    1,700
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks guys. That got it!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •