Check if string exists in JS array


Given an array of strings:

const strings = ['foo', 'bar', 'baz'];

The ways to check if a string exists in a JavaScript array are:

includes

Use includes to check if a string is found in a list:

strings.includes('foo'); // true

In terms of browser support, includes is not supported in Internet Explorer. indexOf can be used instead.

indexOf

Use indexOf to get the index position of a string in a list:

strings.indexOf('foo'); // 0

To check that a string exists in the list:

strings.indexOf('foo') !== -1; // true

for-loop

Of course, you can use a for statement:

let stringMatch = 'foo';
let stringExists = false;

for (let i = 0, len = strings.length, i < len; i++) {
  if (strings[i] === stringMatch) {
    stringExists = true;
    break;
  }
}

stringExists; // true

The main benefit of for statements (instead of forEach or map) is the ability to break or return early.

trie

Lastly, if there are a lot of strings in the array, storing them in a trie may improve performance.

The following example uses the package trieste:

const trie = trieste();
trie.add.apply(trie, strings);
trie.contains('foo'); // true


If you enjoyed this post, please consider supporting this site!