HomeLanguagesJavascriptHow to make Array.indexOf() case insensitive in JavaScript ?

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

The task is to make the Array.indexOf() method case insensitive. Here are a few of the techniques discussed with the help of JavaScript.

Approaches:

Approach 1: Using JavaScript toLowerCase() Method

Transform the search string and elements of the array to the lowercase using the .toLowerCase() method, then perform the simple search. The below example illustrates the method. 

Syntax:

str.toLowerCase()

Example: In this example, we will be searching for an element irrespective of its case and return the index of the element.

Javascript




let arr = ['GFG_1', 'neveropen',
    'Geeksforneveropen', 'GFG_2', 'gfg'];
 
let el = 'gfg_1';
 
function gfg_Run() {
    let res = arr.findIndex(
        item => el.toLowerCase() === item.toLowerCase());
 
    console.log("The index of '" +
        el + "' is '" + res + "'.");
}
 
gfg_Run();


Output

The index of 'gfg_1' is '0'.

Approach 2: Using JavaScript toUpperCase() Method:

Transform the search string and elements of the array to the upper case using the toUpperCase() method, then perform the simple search. The below example illustrates this method. 

Syntax:

str.toUpperCase()

Example: In this example, we will be searching for an element irrespective of its case and return if the element is present in the array or not.

Javascript




let arr = ['GFG_1', 'neveropen',
    'Geeksforneveropen', 'GFG_2', 'gfg'];
 
let el = 'gfg_1';
 
function gfg_Run() {
    let res = arr.find(key => key.toUpperCase()
        === el.toUpperCase()) != undefined;
         
    if (res) {
        res = 'present';
    } else {
        res = 'absent';
    }
 
    console.log("The index of '" +
        el + "' is '" + res + "'.");
}
 
gfg_Run();


Output

The index of 'gfg_1' is 'present'.

RELATED ARTICLES

Most Popular

Dominic
32538 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6920 POSTS0 COMMENTS
Nicole Veronica
12033 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12143 POSTS0 COMMENTS
Shaida Kate Naidoo
7055 POSTS0 COMMENTS
Ted Musemwa
7289 POSTS0 COMMENTS
Thapelo Manthata
7010 POSTS0 COMMENTS
Umr Jansen
6997 POSTS0 COMMENTS