Check whether an array exists in an array of arrays?

Because [1,3] !== [1,3], since objects will only equal if they reference the same object. You need to write your own search routine:

function searchForArray(haystack, needle){
  var i, j, current;
  for(i = 0; i < haystack.length; ++i){
    if(needle.length === haystack[i].length){
      current = haystack[i];
      for(j = 0; j < needle.length && needle[j] === current[j]; ++j);
      if(j === needle.length)
        return i;
    }
  }
  return -1;
}

var arr = [[1,3],[1,2]];
var n   = [1,3];

console.log(searchForArray(arr,n)); // 0

References

  • Using the Equality Operators:

    If both operands are objects, they're compared as objects, and the equality test is true only if both refer the same object.


You can use this

 var a = [ [1,2] , [3,4] ];
 var b = [1,2];
 a = JSON.stringify(a);
 b = JSON.stringify(b);

then you can do just an indexOf() to check if it is present

var c = a.indexOf(b);
if(c != -1){
    console.log('element present');
}

You could iterate the array of arrays with Array#some and then check every item of the inner array with the single array with Array#every.

var array = [1, 3],
    prizes = [[1, 3], [1, 4]],
    includes = prizes.some(a => array.every((v, i) => v === a[i]));

console.log(includes);

Because both these methods use reference equality when operating on objects. The array that exists and the one you are searching for might be structurally identical, but they are unique objects so they won't compare as equal.

This would give the expected result, even if it's not useful in practice:

var myArr = [1,3];
var prizes = [myArr,[1,4]];
prizes.indexOf(myArr);

To do what you wanted you will need to write code that explicitly compares the contents of arrays recursively.

Tags:

Javascript