Borislav Hadzhiev
Sun Oct 03 2021·3 min read
Photo by Darrell Cassell
To do a case insensitive check if an array contains a string in JavaScript:
Array.findIndex
method, passing it a function// Not supported in IE 6-11 const names = ['John', 'Bob', 'Adam']; const name = 'ADAM'; const index = names.findIndex(element => { return element.toLowerCase() === name.toLowerCase(); }); console.log(index); // 👉️ 2
The function we've passed to the Array.findIndex method is called with each element in the array, until the function returns a truthy value or iterates over all of the array's values.
Once the callback function returns a truthy value, the element's index
is
returned from findIndex
.
In the code example, the function returned 2
because the 3rd element in the
array matched the string.
If the function we passed to findIndex
never returns a truthy value, then
findIndex
returns -1
.
const names = ['John', 'Bob', 'Adam']; const name = 'Tim'; const minusOne = names.findIndex(element => { return element.toLowerCase() === name.toLowerCase(); }); console.log(minusOne); // 👉️ -1
To do a case insensitive check if an array contains a string in JavaScript:
Array.some
method, passing it a functiontrue
is returnedThe difference with Array.findIndex
is that the Array.some
method returns
true
or false
, instead of the index of the array element or -1
.
// Supported in IE 9-11 const names = ['John', 'Bob', 'Adam']; const name = 'JOHN'; const includesValue = names.some(element => { return element.toLowerCase() === name.toLowerCase(); }); console.log(includesValue); // 👉️ true
The function we passed to the Array.some method is called with each element of the array until a truthy value is returned or the array's values are exhausted.
IE 9-11
supports the Array.some
method, whereas it doesn't support the Array.find
and Array.findIndex
methods.Array.find
method, passing it a function// Not supported in IE 6-11 const names = ['John', 'Bob', 'Adam']; const name = 'ADAM'; const result = names.find(element => { return element.toLowerCase() === name.toLowerCase(); }); console.log(result); // 👉️ 'Adam'
The function we pass to the Array.find method gets called with each element in the array until it returns a truthy value or the array's values are exhausted.
If the callback function returns a truthy value, then that element is returned
from the Array.find
method.
If all invocations of the callback function return a falsy value, the
Array.find
method returns undefined
.
In the code example, our case insensitive check for adam
succeeded, therefore
Array.find
returned the array element.