Wednesday 6 December 2017

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

itemprop="text">

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 question
href="https://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array">Best
way to find an item in a JavaScript Array?
which addresses finding
objects in an array using indexOf.



Answer





Current browsers have href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Browser_compatibility"
rel="noreferrer">Array#includes, which does
exactly that, href="https://kangax.github.io/compat-table/es2016plus/#test-Array.prototype.includes"
rel="noreferrer">is widely supported, and has a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Polyfill"
rel="noreferrer">polyfill for older
browsers.



> ['joe', 'jane',
'mary'].includes('jane');
true



You can also use
href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf"
rel="noreferrer">Array#indexOf, which is less
direct, but doesn't require Polyfills for out of date
browsers.



jQuery offers href="http://api.jquery.com/jquery.inarray/"
rel="noreferrer">$.inArray, which is functionally
equivalent to
Array#indexOf.




href="http://underscorejs.org/#" rel="noreferrer">underscore.js, a
JavaScript utility library, offers rel="noreferrer">_.contains(list, value), alias
_.include(list, value), both of which use href="http://underscorejs.org/#indexOf" rel="noreferrer">indexOf internally
if passed a JavaScript array.



Some other
frameworks offer similar
methods:





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


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...