Make Array.indexOf() case insensitive in JavaScript


Borislav Hadzhiev

Last updated: Oct 4, 2021


Photo from Unsplash

How to make Array.indexOf() case insensitive #

To get the index of an element by performing case insensitive lookup, we have to:

  1. call the Array.findIndex method with a function
  2. the function should convert the array element and the string to lowercase and do an equality check
  3. the Array.findIndex method returns the element's index or -1 if no elements satisfy the condition
// Not Supported in IE 6-11 const arr = ['HELLO', 'WORLD']; const str = 'world'; const index = arr.findIndex(element => { return element.toLowerCase() === str.toLowerCase(); }); console.log(index); // 👉️ 1 if (index !== -1) { // 👉️ string is in the array }

The function that we passed to the Array.findIndex method gets invoked with each element of the array until it returns a truthy value or iterates over all elements.

In the code snippet, we have converted both the array element and the string to lowercase to make the comparison case insensitive.

The same result could be achieved by converting the element and string to uppercase.

The string is contained in the array at index 1, therefore that's the return value from Array.findIndex.

If the equality comparison never returns true, then Array.findIndex will return -1.

We can't get the index of an element by performing a case insensitive lookup with Array.indexOf, because the method takes in the value directly and does not allow us to iterate over each array element and manipulate them (e.g. lowercase).

Note that Array.findIndex is not supported in Internet Explorer 6-11, so if you have to support the browser, make sure to get a polyfill or use babel to transpile your code to an older version of JavaScript that the browser understands.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.