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

Xavier
  • 1,672
  • 5
  • 27
  • 46

7 Answers7

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

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 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 – hereandnow78 Jun 11 '13 at 10:00
  • @Felix Kling can u please check my edited question and provide me a solution – Xavier Jun 11 '13 at 10:42
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);
    }
  }
}
hereandnow78
  • 14,094
  • 8
  • 42
  • 48
0

try

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

If globalBoolean is true then equal.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • 1
    I need to check each values of the sub_array with main_array not a particular value alone – Xavier Jun 11 '13 at 09:47
  • 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? – Felix Kling Jun 11 '13 at 09:55
  • 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`. – Felix Kling Jun 11 '13 at 09:57
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]+"));
WilQu
  • 7,131
  • 6
  • 30
  • 38
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');
        }
sangram parmar
  • 8,462
  • 2
  • 23
  • 47
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
});
OzrenTkalcecKrznaric
  • 5,535
  • 4
  • 34
  • 57
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");
   });
});
Afroman Makgalemela
  • 690
  • 2
  • 8
  • 21