HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arrayhowcheckincludesvaluejavascript

Problem

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.

Solution

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:

  • jQuery: $.inArray(value, array, [fromIndex])



  • Underscore.js: _.contains(array, value) (also aliased as _.include and _.includes)



  • Dojo Toolkit: dojo.indexOf(array, value, [fromIndex, findLast])



  • Prototype: array.indexOf(value)



  • MooTools: array.indexOf(value)



  • MochiKit: findValue(array, value)



  • MS Ajax: array.indexOf(value)



  • Ext: Ext.Array.contains(array, value)



  • Lodash: _.includes(array, value, [from]) (is _.contains prior 4.0.0)



  • Ramda: R.includes(value, array)



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

Context

Stack Overflow Q#237104, score: 5530

Revisions (0)

No revisions yet.