Categories
algorithm arrays javascript javascript-objects time-complexity

How do I check if an array includes a value in JavaScript?

4668

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

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.

10

  • 59

    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

    Jul 2, 2012 at 11:56

  • 22

    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, 2013 at 7:59

  • 13

    ~ 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, 2014 at 12:49

  • 19

    @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, 2015 at 5:35


  • 7

    The title is misleading. Where is the [[1,2],[3,4]].includes([3,4]) ?

    – mplungjan

    Apr 2, 2017 at 9:20

5130

Modern browsers have Array#includes, which does exactly that and is widely supported by everyone except IE:

console.log(['joe', 'jane', 'mary'].includes('jane')); //true

You can also use Array#indexOf, which is less direct, but doesn’t require polyfills for outdated browsers.

console.log(['joe', 'jane', 'mary'].indexOf('jane') >= 0); //true

Many frameworks also offer similar methods:

Notice that some frameworks implement this as a function, while others add the function to the array prototype.

9

  • 45

    MooTools also has Array.contains that returns a boolean, which sounds like the real question here.

    Jun 8, 2010 at 14:10

  • 23

    prototype also has Array.include that returns a boolean

    Sep 10, 2010 at 22:54

  • 47

    If you are using a good browser, you can just use array.indexOf(object) != -1

    Oct 6, 2010 at 16:17

  • 14

    Also, dont use indexOf alone as a condition, because the first element will return 0 and will be evaluated as falsy

    – plus-

    Feb 29, 2012 at 17:17

  • 261

    inArray is a terrible name for a function that returns the index of the element, and -1 if it doesn’t exist. I would expect a boolean to be returned.

    – Tim

    Jul 22, 2012 at 9:45

484

Update from 2019: This answer is from 2008 (11 years old!) and is not relevant for modern JS usage. The promised performance improvement was based on a benchmark done in browsers of that time. It might not be relevant to modern JS execution contexts. If you need an easy solution, look for other answers. If you need the best performance, benchmark for yourself in the relevant execution environments.

As others have said, the iteration through the array is probably the best way, but it has been proven that a decreasing while loop is the fastest way to iterate in JavaScript. So you may want to rewrite your code as follows:

function contains(a, obj) {
    var i = a.length;
    while (i--) {
       if (a[i] === obj) {
           return true;
       }
    }
    return false;
}

Of course, you may as well extend Array prototype:

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}

And now you can simply use the following:

alert([1, 2, 3].contains(2)); // => true
alert([1, 2, 3].contains('2')); // => false

2

237

indexOf maybe, but it’s a “JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard.”

Example:

[1, 2, 3].indexOf(1) => 0
["foo", "bar", "baz"].indexOf("bar") => 1
[1, 2, 3].indexOf(4) => -1

AFAICS Microsoft does not offer some kind of alternative to this, but you can add similar functionality to arrays in Internet Explorer (and other browsers that don’t support indexOf) if you want to, as a quick Google search reveals (for example, this one).

0