Current browsers have Array#includes
, which does exactly that, is widely supported, and has a polyfill for older browsers.
> ['joe', 'jane', 'mary'].includes('jane');
true
You can also use Array#indexOf
, which is less direct, but doesn't require Polyfills for out of date browsers.
jQuery offers $.inArray
, which is functionally equivalent to Array#indexOf
.
underscore.js, a JavaScript utility library, offers _.contains(list, value)
, alias _.include(list, value)
, both of which use indexOf internally if passed a JavaScript array.
Some other frameworks offer similar methods:
- 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) - ECMAScript 2016:
array.includes(value)
Notice that some frameworks implement this as a function, while others add the function to the array prototype.