Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find part of a string in array jQuery

I've been trying to find a portion of a string in a couple of Array of strings without success:

I have array1 ['BA11', 'BA14', 'BA15']

and array2 ['GL156', 'GL24', 'GL31']

I wanted that it would return true when I searched for just part of the string "BA11AB", "BA15HB" or "GL156DC".

Here is the code I've been using but without success:

if($.inArray(userinput, array1) !== -1) 
        {
            alert("Found in Array1!");
        }

if($.inArray(userinput, array2) !== -1) 
        {
            alert("Found! in Array2");
        }

Thanks Nuno

like image 518
Nuno Luz Avatar asked Dec 08 '22 11:12

Nuno Luz


1 Answers

Seeing that OP changed his original question: http://jsfiddle.net/c4qPX/2/ is a solution for both of them (there's no really difference for the algorithm if we're searching through the array of searched keys or searched values) - the point is what to compare.

var array1 = ['BA11', 'BA14', 'BA15'];
var array2 = ['GL156', 'GL24', 'GL31'];
var search = 'GL156DC';

$.each([array1, array2], function(index, value){
    $.each(value, function(key, cell){
        if (search.indexOf(cell) !== -1)
            console.log('found in array '+index, cell);
    });
});
like image 102
eithed Avatar answered Dec 23 '22 05:12

eithed