walid mahmoud
Published in : 2022-02-13

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

Javascript

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?

Comments

Yasen Sayed Date : 2022-02-13

Best answers

8

Best answers

8

You can use this in the modern browsers, code to check the array
 

console.log(['joe', 'jane', 'mary'].includes('jane')); //true

Also, you can the indexOf method like this:
 

console.log(['joe', 'jane', 'mary'].indexOf('jane') >= 0); //true

Joseph Morgan Date : 2022-02-13

Best answers

11

Best answers

11

let arr = ['orange', 'blue', 'red'];let index = arr.indexOf('blue');if(index > -1){//Exists console.log(arr[index]);}

also, you can use this way using indexOf 

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

Javascript: Filtering arrays by it properties?
Publish date: 2022-03-05 | Comments: 1

Tag: Javascript

How to get audio input and audio output as one stream?
Publish date: 2022-02-13 | Comments: 2

Tag: Javascript

Vanilla JavaScript Next & prev Navigation
Publish date: 2022-02-22 | Comments: 1

Tag: Javascript

Coping plain text into form bug.
Publish date: 2022-02-11 | Comments: 1

Tag: Javascript

How select specific tag in jQuery using if else statement?
Publish date: 2022-02-27 | Comments: 1

Tag: Javascript

How to open URL in new tab & focus on it in Javascript?
Publish date: 2021-12-22 | Comments: 1

Tag: Javascript

javascript: Uncaught TypeError: undefined is not a function
Publish date: 2022-03-02 | Comments: 2

Tag: Javascript