Share:

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

What is the most concise and efficient way to find out if a JavaScript array contains a value?
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.

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.

Comments

Popular posts from this blog

Get Color From Pixel C# WPF | Saatody | Amit Padhiyar

Basic Audio Operations With MP3 And Wave Files Using NAudio C#

Create Drag And Drop Operation Between DevExpress GridControl And Custom WPF UI | Saatody | Amit Padhiyar