Richard Richard - 1 year ago 65
Javascript Question

Check whether an array exists in an array of arrays?

I'm using JavaScript, and would like to check whether an array exists in an array of arrays.

Here is my code, along with the return values:

var myArr = [1,3];
var prizes = [[1,3],[1,4]];


It's the same in jQuery:

$.inArray(myArr, prizes);

Why is this returning -1 when the element is present in the array?

Answer Source

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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download