0

I have a strange problem. I have a Javascript nested array and I would like to test for containment of an array in the nest:

var arr1, arr2;
arr1 = [[1, 2], [0, -1]];
arr2 = [1, 2];
if (arr1.indexOf(arr2) > -1)
   alert("success!");

However, the above code returns false for the containment test. Any efficient suggestions on the fix?

Quanquan Liu
  • 1,427
  • 3
  • 16
  • 30
  • Going to have to loop and compare. http://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript – epascarello Sep 01 '15 at 17:28

2 Answers2

0

From the documentation

indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).

For reference - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

To compare objects, you need to loop through the array as suggested by @epascarello in comments.

Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

Assuming that arr1 is always an array of arrays, you can use Array.prototype.some and Array.prototype.every to do this fairly efficiently.

var isContained = arr1.some(function(arr){
    return arr2.length == arr.length && 
        arr2.every(function(item,idx){
            return item == arr[idx];
        });
});
Nikhil Batra
  • 3,118
  • 14
  • 19
spender
  • 117,338
  • 33
  • 229
  • 351