How to make Array.indexOf() case insensitive in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 04 20212 min read

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
index.js
// 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.

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