Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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', 'geeks',
    'Geeksforgeeks', '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', 'geeks',
    'Geeksforgeeks', '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'.



Last Updated : 13 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads