Borislav Hadzhiev
Mon Oct 04 2021·2 min read
Photo by Olya Kuzovkina
To get the index of an element by performing case insensitive lookup, we have to:
Array.findIndex
method with a functionArray.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.
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
.
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.