Check if a String is contained in an Array in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 16 20212 min read

banner

Photo by Joshua Earle

Check if a String is contained in an Array #

To check if a string is contained in an array, call the includes() method, passing it the string as a parameter. The includes method will return true if the string is contained in the array and false otherwise.

index.js
const arr = ['one', 'two', 'three']; if (arr.includes('two')) { console.log('โœ… String is contained in Array'); } else { console.log('โ›”๏ธ String is NOT contained in Array'); }

We used the Array.includes method to determine if the string two is contained in the array.

The includes method returns true if the provided value is found in the array and false otherwise.

Note that the includes method performs a case sensitive comparison.

If you need a case insensitive check whether a string is contained in an array, use the Array.some method instead.

index.js
const arr = ['one', 'two', 'three']; const two = 'TWO'; const containsString = arr.some(element => { return element.toLowerCase() === two.toLowerCase(); }); console.log(containsString); // ๐Ÿ‘‰๏ธ true

The function we passed to the some method gets called with each element in the array until it returns a truthy value or iterates over all array elements.

We convert both, the array element and the string to lowercase to perform case insensitive comparison.

If the function we passed to the some method returns a truthy value at least once, the method short-circuits and returns true.

The includes method is not supported in Internet Explorer. If you need to support the browser, use the next approach covered in this article.

Check if a String is contained in an Array using indexOf #

To check if a string is contained in an array, call the indexOf method, passing it the string as a parameter. The indexOf method returns the index of the first occurrence of the string in the array, or -1 if the string is not contained in the array.

index.js
const arr = ['one', 'two', 'three']; if (arr.indexOf('two') !== -1) { console.log('โœ… String is contained in Array'); } else { console.log('โ›”๏ธ String is NOT contained in Array'); }

We use the Array.indexOf method to check if the string two is contained in the array.

If the string is not contained in the array, the indexOf method returns -1, otherwise it returns the index of the first occurrence of the string in the array.

This approach is definitely not as direct and readable as using the includes method, however if you have to support Internet Explorer, it gets the job done.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee