Case insensitive search in array | Javascript

Case insensitive search in array | Javascript

Added by Nasir Mahmood updated on Friday, November 17, 2017

Problem:

JavaScript provide a Method indexOf() which is used to search object from array but this is case sensitive.

Jquery provide a method jQuery.inArray() To search object in array but this is case sensitive also i.e “a” is not equal to “A”.

Following is small javascript function which return index of object if found in array otherwise return -1 and this is case insensitive method.

function SearchArray( element, array ) {
    var len = array.length, str = element.toString().toLowerCase();
    for ( var i = 0; i < len; i++ ) {
        if ( array[i].toLowerCase() == str ) { return i; }
    }
    return -1;
}
                

Usage:

    var array_data = [];
    array_data.push( 1 );
    array_data.push( 2 );
    array_data.push( 3 );    
    array_data.push( 4 );
    array_data.push( 5 );
    if ( SearchArray( 5, array_data ) == -1 ) {
        alert('not found');
    }
            
                

Related Tags

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected