Explain Codes LogoExplain Codes Logo

How to check if a string array contains one string in JavaScript?

javascript
prompt-engineering
functions
best-practices
Alex KataevbyAlex Kataev·Dec 19, 2024
TLDR

The includes() method is your quick and easy solution to identify if a string is in an array:

const fruits = ['apple', 'banana', 'mango']; const found = fruits.includes('banana'); // true, 'banana' is in the house

It will return true if 'banana' is partying with the fruits, otherwise false - the party's a bore without 'banana'.

Digging Deeper: Case sensitivity and indexOf

Hang on to your hats, because the includes() method is case-sensitive. It differentiates between 'Banana' and 'banana', essentially having a it's-not-you-it's-me moment. You can circumvent this by ensuring all strings are in the same case:

const search = 'Banana'.toLowerCase(); const found = fruits.includes(search); // true, 'banana' now fits dress code

includes() is not invited to the IE 8 and lower party. In this case, use the indexOf() method which finds the index of the found element, or -1 if it's MIA:

const index = fruits.indexOf('banana'); const found = index > -1; // true, 'banana' is still in the house

For inviting includes() to old parties, MDN has a polyfill - essentially a golden ticket.

Extending the Party Invite: Array Prototypes

Making the Array prototype extend the contains method might feel like a shortcut:

if (!Array.prototype.contains) { Array.prototype.contains = function(str) { return this.includes(str); }; }

However, but it's like adding a new rule to Cards Against Humanity mid-game - quirky, unpredictable, and causing unexpected behaviors.

You don’t want an empty array to crash the party:

const isEmpty = []; // Empty party isEmpty.includes('anything'); // false, because there's nobody to hang

Also, be on the lookout when the search string is empty:

const fruits = ['apple', 'banana', 'mango']; fruits.includes(''); // true, because it seems '' has a VIP pass to any string party

Consider some(), the clever cousin of includes(), for complex checks:

const hasTropicalFruit = fruits.some(fruit => fruit === 'mango' || fruit === 'papaya');

Common Pitfalls & Safe Practices

Manually checking each guest via a loop could work in a pinch but invokes the formal tedium of a Victorian dance:

let found; for (let i = 0; i < fruits.length; i++) { if (fruits[i] === 'banana') { found = true; // "One banana, ah-ah-ah!" break; } }

Lean on built-in methods for efficiency and readability:

return fruits.includes('banana'); // Direct 'banana' guest check

Ensure to validate inputs. Do not presume the nature of the arguments passed:

function containsString(array, str) { if (!Array.isArray(array) || typeof str !== 'string') { throw new TypeError('Wrong! Try again.'); } return array.includes(str); }