Saturday, July 11, 2015

Case insensitive search in array | Javascript

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;
                         }

  • 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');
  • }
  • 0 comments:

    Post a Comment

    Twitter Delicious Facebook Digg Stumbleupon Favorites More