Xavier
Xavier

Reputation: 1794

How to check if a particular characters are available in a javascript string array

I have a javascript array like

var main_array = ["allen~1", "ajay~2", "raj~3"];

I have another array like

var sub_array=["allen", "ajay"];

EDIT

I need to check whether each values of sub_array is found in main_array, (i.e) whether 'allen' found in ["allen~1", "ajay~2", "raj~3"] so the values which do not match must be removed from the array. As the result "raj~3" must be removed from the main_array

How to achieve this?

I have tried indexOf(), match() but that fails since it expects an exact match like "allen~1"..

Thanks in advance

Upvotes: 0

Views: 2125

Answers (7)

hereandnow78
hereandnow78

Reputation: 14434

your question is kind if not so clear, but i think what you want to achieve is an array which contains all values from main_array which are part of sub_array? in your example the resulting array should be

["allen~1", "ajay~2"]

? if so see this:

then you need to loop over your sub-array, and check in your main_array:

var i, j, result = [];
for (i = 0; i < sub_array.length; i++) {
  for (j = 0; j < main_array.length; j++) {
    if (main_array[j].indexOf(sub_array[i]) != -1) {
      result.push(main_array[j]);
    }
  }
}

see a working jsfiddle: http://jsfiddle.net/yf7Dw/

edit: Felix Kings answer is probably best, but if you dont want to use polyfills and must support older IE's you could use my solution

edit2: Array.splice is your friend if you want to remove the element from the main array. see the updated fiddle: http://jsfiddle.net/yf7Dw/2/

var i, j;
for (i = 0; i < sub_array.length; i++) {
  for (j = 0; j < main_array.length; j++) {
    if (main_array[j].indexOf(sub_array[i]) != -1) {
      main_array.splice(j, 1);
    }
  }
}

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816850

You can use .every [MDN] and .some [MDN]:

var all_contained = sub_array.every(function(str) {
    return main_array.some(function(v) {
        return v.indexOf(str) > -1;
    });
});

Have a look at the documentation for polyfills for older IE versions.


If you want to remove elements, you can use .filter [MDN] and a regular expression:

// creates /allen|ajay/
var pattern = new RegExp(sub_array.join('|'));
var filtered = main_array.filter(function(value) {
    return pattern.test(value);
});

Values for which the test returns false are not included in the final array.

If the values in sub_array can contain special regular expression characters, you have to escape them first: Is there a RegExp.escape function in Javascript?.

Upvotes: 1

Afroman Makgalemela
Afroman Makgalemela

Reputation: 740

Get underscore js. Then do this:

var myarray = ["Iam","Iamme","meIam"];
var sub_ar = ["am", "amI", "amme"];
_.each(myarray, function(x){
    _.each(sub_ar, function(y){
        if(x == y)
        {
           console.log(y + " is a match");
    });
 });

Sorry. This wont work because you are looking for substring. My bad. Try this:

var myarray = ["Iam","Iamme","meIam"];
var sub_ar = ["am", "amI", "amme"];
_.each(myarray, function(x){
   _.each(sub_ar, function(y){
      if(x.indexOf(y) !== -1)
      {
        console.log("match found");
   });
});

Upvotes: 0

OzrenTkalcecKrznaric
OzrenTkalcecKrznaric

Reputation: 5646

Just another solution...

var filtered_array = jQuery.grep(main_array, function(n1, i1){
    var y = jQuery.grep(sub_array, function(n2, i2){
        return n1.indexOf(n2) !== -1; // substring found?
    });
    return y.length; // 0 == false
});

Upvotes: 0

sangram parmar
sangram parmar

Reputation: 8736

try

            var main_array = ["allen~1", "ajay~2", "raj~3"];
        var main_array1 = new Array();

        for (var i = 0; i < main_array.length; i++) {
            main_array1.push(main_array[i].split('~')[0])
        }
        var sub_array = ["allen", "ajay"];
        if ($.inArray('allen', main_array1) == -1) {
            alert('false');
        }
        else {
            alert('true');
        }

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122006

try

var globalBoolean  =true;
$.each(subarray, function (index,value) {
    if ( !($.inArray(value, main_array) > -1)){
     globalBoolean =false;
    }
});

If globalBoolean is true then equal.

Upvotes: 0

WilQu
WilQu

Reputation: 7393

Build a RegExp from the searched string and use match with it

string.match(new RegExp(searchedString + ".*"));

or

string.match(new RegExp(searchedString + "~[0-9]+"));

Upvotes: 0

Related Questions