0

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

1
  • What should happen if main_array doesn't contain "ajay~2"? Commented Jun 11, 2013 at 10:51

7 Answers 7

1

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);
    }
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

can u please check my edited question and provide me a solution
But actually it removes ["allen~1", "ajay~2"] but i want to remove "raj~3" which is not available in sub_array..
so my first solution was correct... just replace main_array with the result var after the loop... -> main_array = result;
1

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?.

2 Comments

this is probably the best answer for your problem, if you dont want to use polyfills, but need to support older ie-versions see my answer
@Felix Kling can u please check my edited question and provide me a solution
0

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]+"));

Comments

0

try

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

If globalBoolean is true then equal.

3 Comments

I need to check each values of the sub_array with main_array not a particular value alone
You are iterating over each element in main_array. Of course each of those elements will be contained in main_array. Did you mean to use sub_array somewhere?
I see. It still won't work because each value in sub_array is only a substring of the values in main_array. $.inArray will always yield -1.
0

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.