Javascript: check if an array contains a string

Authors
  • avatar
    Name
    Hamza Rahman
Published on
-
2 mins read
-

Two related questions come up a lot, and they are the reverse of each other. This post covers both: checking whether an array contains a given string, and checking whether a string contains any element from an array.

Check if an array contains a string

The cleanest way is Array.prototype.includes(), which returns true or false.

const fruits = ['apples', 'grapes', 'watermelons', 'mangoes']
fruits.includes('grapes') // true
fruits.includes('pizza') // false

If you also need the position, use indexOf. It returns the index, or -1 when the value is not found.

fruits.indexOf('grapes') // 1
fruits.indexOf('pizza') // -1
fruits.indexOf('grapes') !== -1 // true

For a case-insensitive check, or to match on part of each entry, use .some() with your own test.

const hasGrapes = fruits.some((fruit) => fruit.toLowerCase() === 'grapes')

Check if a string contains any array element

This is the inverse: given a sentence and a list of words, is any word in the sentence? The .some() method paired with String.prototype.includes() does it in one line.

const stringTODO = 'bring some apples for guests'
const stringTODOFalsely = 'bring pizza for guests'
const basket = ['apples', 'grapes', 'watermelons', 'mangoes']
const hasFruit = basket.some((fruit) => stringTODO.includes(fruit))
const hasPizza = basket.some((fruit) => stringTODOFalsely.includes(fruit))
console.log('hasFruit:', hasFruit, '\nhasPizza:', hasPizza)

Output:

hasFruit: true
hasPizza: false

.some() runs the test for each array element and returns true as soon as one matches, so stringTODO.includes(fruit) checks whether the sentence contains that word.