Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to jquery .inarray?

I love how inarray, searchs an array without looping, but it only does exact/precise matches, where if i used the .match, i can do partial matches, but that requires a loop.

Is there any way to search an array for partial matches, without looping?

There are 2 arrays, 1 to be searched for, the 2nd to replace the text/values if a partial or full match is found in the 1st.

The goal is to have the fastest way to search the array for partial or full matches.

Any suggestions?

like image 378
crosenblum Avatar asked Dec 22 '22 17:12

crosenblum


1 Answers

Well, .inArray() of course loops over the Array if Array.prototype.indexOf() is not available:

snippet

inArray: function( elem, array ) {
    if ( array.indexOf ) {
        return array.indexOf( elem );
    }

    for ( var i = 0, length = array.length; i < length; i++ ) {
        if ( array[ i ] === elem ) {
            return i;
        }
    }

    return -1;
},

snippet

If you just want to know whether or not an entry is contained by an Array, you may just want to .join() it and use the String.prototype.indexOf().

This of course, can't return an index anymore. So you would need to write your own logic. Could be done easily by modifying the above code. For instance:

Array.prototype.ourIndexOf = function(v) {
    for ( var i = 0, length = this.length; i < length; i++ ) {
       if ( typeof this[i] === 'string' && this[i].indexOf(v) > -1 ) {
            return i;
       }
    }
    return -1;
};

['Foobar', 'baseball', 'test123'].ourIndexOf('base') // === 1
like image 62
jAndy Avatar answered Jan 01 '23 07:01

jAndy