Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How would I check if an array carries a value in JavaScript?

What is the briefest and proficient approach to see whether a JavaScript array contains a value?

This is the lone 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 superior and more compact approach to achieve this?
by

2 Answers

sandhya6gczb
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
MounikaDasa
Use:

function isInArray(array, search)
{
return array.indexOf(search) >= 0;
}

// Usage
if(isInArray(my_array, "my_value"))
{
//...
}

Login / Signup to Answer the Question.