search

Home  >  Q&A  >  body text

How to check if an array contains a value in JavaScript?

<p>What is the cleanest, most efficient way to find out whether a JavaScript array contains a value? </p> <p>This is the only way I know:</p> <pre class="brush:php;toolbar:false;">function contains(a, obj) { for (var i = 0; i < a.length; i ) { if (a[i] === obj) { return true; } } return false; }</pre> <p>Is there a better, cleaner way to achieve this? </p> <p>This is related to the Stack Overflow question <em>What is the best way to find items in a JavaScript array? </em> Closely related, this question addresses finding objects in an array using <code>indexOf</code>. </p>
P粉592085423P粉592085423460 days ago443

reply all(2)I'll reply

  • P粉788571316

    P粉7885713162023-08-24 00:43:22

    2019 Update: This answer is from 2008 (11 years old!) and has nothing to do with modern JS usage. Promised performance improvements are based on benchmark testing completed in the browser at that time. It may not be relevant to modern JS execution context. If you need a simple solution, look for other answers. If you need the best performance, benchmark yourself in a relevant execution environment.

    As others have said, iterating through an array is probably the best way to do it, but it has been proven that a descending while loop is the fastest way to iterate in JavaScript . Therefore, you may need to rewrite the code as follows:

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

    Of course, you can also extend the Array prototype:

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

    Now you can simply use the following:

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

    reply
    0
  • P粉076987386

    P粉0769873862023-08-24 00:14:12

    Modern browsers have Array#includes which do exactly that and are widely used by everyone except IE support:

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

    reply
    0
  • Cancelreply