2

Possible Duplicate:
Javascript - array.contains(obj)

What's wrong with this:

var zipCodes =(['90001','90002','90003']);

Test if the value exists in the array zipCodes

if('90001' in zipCodes) {
  alert('True');
};
Community
  • 1
  • 1
djreed
  • 2,673
  • 4
  • 22
  • 21
  • 1
    See http://stackoverflow.com/questions/237104/javascript-array-containsobj – Jon Gauthier Jul 10 '11 at 00:24
  • 2
    If this is all there is to your code, then don't use an array as it's the wrong tool for the job. Use an object instead and then you can use "in". See my post below. – jfriend00 Jul 10 '11 at 00:40

5 Answers5

12

The in operator looks at property names, not values.

Because it's an Array, the property names will be the indices of the Array.

If you're only supporting a modern environment, you could use Array.prototype.indexOf().

if(zipCodes.indexOf('90001') > -1) {

If you need to support environments that don't have .indexOf(), you could implement the MDN fix.

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";

        if (this === void 0 || this === null) throw new TypeError();

        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) return -1;

        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n !== n) // shortcut for verifying if it's NaN
            n = 0;
            else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) n = (n > 0 || -1) * Math.floor(Math.abs(n));
        }

        if (n >= len) return -1;

        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);

        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) return k;
        }
        return -1;
    };
}
user113716
  • 318,772
  • 63
  • 451
  • 440
4

If you want to check if the array contains a given value, you can use the indexOf method to check for the position of an item. If the item is not found in the array, a -1 is returned:

var zipCodes =(['90001','90002','90003']);
zipCodes.indexOf('90001') // 0
zipCodes.indexOf('90002') // 1
zipCodes.indexOf('90003') // 2
zipCodes.indexOf('90004') // -1

if(zipCodes.indexOf('90001') != -1) {
  alert('True');
};

See more at http://freewebdesigntutorials.com/javaScriptTutorials/jsStringObject/indexOfMethod.htm

Ben Simpson
  • 4,009
  • 1
  • 18
  • 10
  • The `indexOf` method on Array objects is very new, so he might not be able to use it. If an array is a must, then `zipCodes.join().indexOf('90002')` would work. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf for information on the availability of `indexOf`. – James Sumners Jul 10 '11 at 02:16
3

Use an object instead. If this is all you're trying to do with the array, then an object is a much more efficient way to do a lookup list.

var zipCodes = {"90001": true, "90002": true, "90003": true};

if ('90001' in zipCodes) {
    alert('True');
}

jsfiddle here to see it work: http://jsfiddle.net/jfriend00/ZNGTq/

jfriend00
  • 683,504
  • 96
  • 985
  • 979
2

You need something like this:

var zipCodes =(['90001','90002','90003']);

if (zipCodes.has('90001')) {
  ....
}

    Array.prototype.has=function(v){
        for (i=0;i<this.length;i++){
           if (this[i]==v) return i;
        }
        return false;
    }

See this for more info:

http://snook.ca/archives/javascript/testing_for_a_v

....

PaulM
  • 3,281
  • 3
  • 28
  • 38
  • Thanks for the downvote and no comment. – PaulM Jul 10 '11 at 00:26
  • An array isn't the best data structure for this type of test unless there are other reason for it to be an array. Better to use an object. – jfriend00 Jul 10 '11 at 00:28
  • 2
    The title says: Find element in Javascript Array.. Did you miss the "Array" part? I'm just answering the question. Go comment in the OP about the data structure, not here! I'm also wondering if the people who downvoted me, have also actually read the accompanied link lol. – PaulM Jul 10 '11 at 00:29
  • My answer is exactly the same as Kon. Fools.. – PaulM Jul 10 '11 at 00:33
  • OK fine. Edit your post a bit and I can undo the down-vote. I just think it's dumb to educate someone on the wrong way to solve a problem (without telling them there's a better way), but I'll undo my downvote when SO lets me because you were answering the literal question. Right now, it won't let me undo the downvote until you edit your post. – jfriend00 Jul 10 '11 at 00:38
  • Posted edited. Hey don't shoot the messenger, comment on the OP post and educate him. Better yet, make an answer! :) – PaulM Jul 10 '11 at 00:41
  • I have done both. I've made an answer and commented to the OP. – jfriend00 Jul 10 '11 at 00:43
  • 1
    I'm not a downvoter, but I would like to comment that adding properties to built-in objects like Array is controversial. Many JavaScript programmers avoid doing such things, so that may have been the reason for one of the downvotes. Just sayin' :) – Ray Toal Jul 10 '11 at 00:45
  • @jfriend00, thanks and I +1 your comment to the OP. @Ray, didn't know. Thanks. – PaulM Jul 10 '11 at 00:51
  • 2
    @PaulM: It's a perfectly legitimate practice. The only problems it causes arise with misuse of the language, or with collisions with other code that is doing the same thing. A developer should use the language correctly, and they should know what the code they're loading does. – user113716 Jul 10 '11 at 00:56
0

Because in checks for a property of an object. Check this out for converting "in object" to "in array": Testing for a Value in JavaScript Array

Kon
  • 27,113
  • 11
  • 60
  • 86