4

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

Nuno Luz
  • 97
  • 1
  • 1
  • 6
  • 3
    Loop the array and use `indexOf` on each string. – elclanrs Dec 03 '13 at 09:55
  • possible duplicate of [How can I check if one string contains another substring in JavaScript?](http://stackoverflow.com/questions/1789945/how-can-i-check-if-one-string-contains-another-substring-in-javascript) – Igl3 Dec 03 '13 at 09:56
  • You don't want to check if the value is in array. You want to check if the value is in one of the arrays values. – eithed Dec 03 '13 at 10:00
  • You can use JavaScript search function http://msdn.microsoft.com/en-us/library/ie/tbc7a78k(v=vs.94).aspx – AurA Dec 03 '13 at 10:06

5 Answers5

5
var found = false;
$.each(array, function(i, val) {
    if (val.indexOf(string) >= 0) {
        found = true;
        return false;
    }
});
Maurice Perry
  • 32,610
  • 9
  • 70
  • 97
  • Works fine, +1!. And here I've prepared a little [jsFiddle](http://jsfiddle.net/Looqntup/) to try it. N.B.: I've encapsulated into a handy function. – Matt Nov 23 '15 at 14:30
  • 1
    @Maurice is it not string.indexOf(val), because val is always the same length, and the string length can be variable and val can be a part of the string, not the other way around. – Bunkerbuster Mar 26 '18 at 20:29
5

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);
    });
});
eithed
  • 3,933
  • 6
  • 40
  • 60
3

You can create a simple function and add it to the Array prototype (so that it can be called on any array) which searches through the array looking for sub-string matches:

JSFIDDLE

Array.prototype.containsSubString = function( text ){
    for ( var i = 0; i < this.length; ++i )
    {
        if ( this[i].toString().indexOf( text ) != -1 )
            return i;
    }
    return -1;
}

Then just use it on your arrays:

var array1 = ['12345', '78273', '34784'],
    array2 = ['JJJJJ', 'ABCDEF', 'FFDDFF'];

if( array1.containsSubString( 234 ) !== -1) 
{
    alert("Found in Array1!");
}

if( array2.containsSubString( 'DD' ) !== -1) 
{
    alert("Found! in Array2");
}

Edit

If you want to find whether an array has an element which is a sub-string of another string then:

JSFIDDLE

Array.prototype.hasSubStringOf = function( text ){
    for ( var i = 0; i < this.length; ++i )
    {
        if ( text.toString().indexOf( this[i].toString() ) != -1 )
            return i;
    }
    return -1;
}

var array3 = [ 'AB11' ];

if( array3.hasSubStringOf( 'AB11HA' ) !== -1) 
{
    alert("Array3 contains substring");
}

Edit 2

Just combine both the previous functions:

JSFIDDLE

Array.prototype.containsSubStringOrHasSubstringOf = function( text ){
    for ( var i = 0; i < this.length; ++i )
    {
        if (    this[i].toString().indexOf( text.toString() ) != -1
             || text.toString().indexOf( this[i].toString() ) != -1 )
            return i;
    }
    return -1;
}

var testArrays = [
        ['BA11ABC', 'BAGL156DC14', 'BA15HC'],
        ['GL156DC', 'GL166DC', 'GL31BA11AB'],
        ['BA11', 'BA14', 'BA15'],
        ['GL156', 'GL24', 'GL31']
    ],
    testValues   = [ "BA11AB", "BA15HB", "GL156DC" ],
    results = [ 'Results:' ];

var test = function( str, arr ){
    var i = arr.containsSubStringOrHasSubstringOf( str );
    if ( i !== -1 )
        results.push( JSON.stringify( arr ) + ' matches ' + str + ' on ' + arr[i] );
    else
        results.push( JSON.stringify( arr ) + ' does not match ' + str );
};

for ( var i = 0; i < testArrays.length; ++i )
    for ( var j = 0; j < testValues.length; ++j )
        test( testValues[j], testArrays[i] );

alert( results.join('\n') );
MT0
  • 143,790
  • 11
  • 59
  • 117
  • If you have a problem extending native JS objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain#Bad_practice.3A_Extension_of_native_prototypes you can define the function as a "normal" function and call it the following way: `containsSubString.call(array1,"234");` – HMR Dec 03 '13 at 11:02
  • Hi, thank you for the answer however if the user inputs a value such as "AB11HB" and I I have an entry on my array that I want this to match, such as "AB11" it will return false. – Nuno Luz Dec 03 '13 at 16:21
  • That is not what you asked for in your original post and none of your examples are like that. – MT0 Dec 03 '13 at 16:34
  • Edit added - if that does not do what you want then please make it explicitly clear what your requirements are and provide a decent set of test data and pass/fail criteria. – MT0 Dec 03 '13 at 16:41
  • Thank you for your answer, what I asked for is the same thing. The only difference is in the data I want to compare. And this is where I am having trouble since if I compare a string which is larger than the data on the array it will always returns false even if part of the string is present in the array. – Nuno Luz Dec 04 '13 at 12:49
  • Edit added - combining the previous two methods. – MT0 Dec 04 '13 at 21:39
1

try something like this

 return array1.toString().indexOf(userinput)!=-1;

if problem with comma than

 return array1.join('|').indexOf(userinput)!=-1;

use space if any problem arrive

return array1.join(' ').indexOf(userinput)!=-1;
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40
  • 1
    A nice approach, but if he searches for `345,7`, it will be found in array1. – eithed Dec 03 '13 at 10:02
  • 2
    Any `join` approach is doomed, as we don't know the OPs data. True, you can separate them with magic characters hoping they won't appear. – eithed Dec 03 '13 at 10:09
  • `var array1 = [ 'A A', 'A,A', 'A|A' ];` and with `userinput` of `'A A'` or `'A,A'` or `'A|A'` then there can be matches across the boundary between array elements with each of your tests. – MT0 Dec 03 '13 at 10:32
0

I'm not sure if you are familiar with underscore js, but you could use something like this:

var array = ['JJJJJ', 'ABCDEF', 'FFDDFF'];
var search = "JJJ";
var found = _.some(array, function(value) {
    return value.indexOf(search)!=-1;
});

alert(found);

see fiddle.

seen the answers of the others and I really like the toString() answers: array.toString().indexOf(search)!=-1

R. Oosterholt
  • 7,720
  • 2
  • 53
  • 77
  • 1
    updated jQuery [fiddle](http://jsfiddle.net/c4qPX/1/) to stop when string is found – R. Oosterholt Dec 03 '13 at 10:23
  • tried which one, underscore or jQuery one? And what didn't work? – R. Oosterholt Dec 03 '13 at 18:29
  • Yes, the second one works, but I need it to find partial results, such returning true if the user inputed "BA11HB" and it would partially correspond to this entry on the array: "BA11". – Nuno Luz Dec 04 '13 at 12:55
  • you could use `join('SEPERATOR')` (e.g. array1.join('|')) to fix this. The first solution is bullet proof (no hassle with choosing the correct separator). – R. Oosterholt Dec 04 '13 at 13:35