user image

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

How to move a div with its content to TinyMEC editor?
Publish date: 2022-02-11 | Comments: 0

Tag: Javascript

Can I read a local json, image or text file from Javascript?
Publish date: 2022-03-03 | 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

jquery undefined function
Publish date: 2022-02-28 | Comments: 1

Tag: Javascript

Check if div have touch another div
Publish date: 2022-03-02 | Comments: 1

Tag: Javascript

Simple HTML date picker is showing not showing calendar icon!
Publish date: 2022-03-01 | Comments: 2

Tag: Javascript

JAVASCRIPT: How do I add another key to object?
Publish date: 2022-03-06 | Comments: 3

Tag: Javascript

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

Tag: Javascript