开发者

Check if an array is inside an array

开发者 https://www.devze.com 2023-04-11 10:22 出处:网络
The title should explain my question. I have an array: a = [[1,2],[1,3],[1,4]]; H开发者_开发知识库ow can I check if the array [1,2] is inside the array a?That depends on the situation.

The title should explain my question.

I have an array:

a = [[1,2],[1,3],[1,4]];

H开发者_开发知识库ow can I check if the array [1,2] is inside the array a?


That depends on the situation.

given

var a = [1,2], b = [1,3], c = [a,b];

We can check easily if a resides in c, if we have c to test on.

for(var i=0,d;d=c[i];i++) {
  if(d === a) {
    //a is inside c
  }
}

or even simpler for browser that supports it (ie7 doesn't)

if(c.indexOf(a) != -1) {
  //a is inside c
}

But if we only have a, and a is not a local variable and we wish to know if it exists inside any array, then we can't, since a is a reference to an object and we can't possibly know if a reference to it exists elsewhere outside our current scope.


if you have a reference, the you can use the == operator. else you have to write your own method to test values. something like this:

function someMethod(testArr, wanted){
  for (i=0; i<testArr.length; i++){
    if(array_diff(testArr[i], wanted).length==0 && array_diff(wanted, $subArr).length==0){
      return true;
    }
  }
  return false;
}

function array_diff(a1, a2)
{
  var a=[], diff=[];
  for(var i=0;i<a1.length;i++)
    a[a1[i]]=true;
  for(var i=0;i<a2.length;i++)
    if(a[a2[i]]) delete a[a2[i]];
    else a[a2[i]]=true;
  for(var k in a)
    diff.push(k);
  return diff;
}


If your array contains numbers or texts only, you can join each array into string, then compare if a string is inside the other.

var a = [[1,2],[1,3],[1,4]];
var b = [1,2]

var aStr = '@' + a.join('@') + '@'
var bStr = '@' + b.join() + '@'

if (aStr.indexOf(bStr) > -1){
   alert ('b is inside a')
}else{
   alert ('b is not inside a')
}


You can try this if your array elements are non-nested arrays.

return JSON.stringify([[1,2],[1,3],[1,4]]).indexOf(JSON.stringify([1,2]))  > 0

This checks if the JSON representation of [1,2] is contained in the JSON representation of [[1,2],[1,3],[1,4]]

But in this case it gives a false positive

return JSON.stringify([[[1,2]],[1,3],[1,4]]).indexOf(JSON.stringify([1,2])) > 0

returns true.


You can also loop through the array object and for each of it's item you can use jQuery.isArray() to determine if the object is an array.

0

精彩评论

暂无评论...
验证码 换一张
取 消