0

There are many ways to check if a value is in an array in Javascript. One could extend the Array prototype or one could make use of the in statement.

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}

> [1,2,3].contains(2)
true
> 3 in [1,2,3]
true 

Why does this not work for lists in lists?

> [[1],[2],[3]].contains([2])
false 
> [3] in [1,2,[3]]
false 

Surely there should be a simple function for what I am trying to do here?

cantdutchthis
  • 31,949
  • 17
  • 74
  • 114
  • You need a deep comparison: http://stackoverflow.com/questions/1068834/object-comparison-in-javascript –  May 24 '13 at 21:59

1 Answers1

0

[2] and [2] are two different objects that happen to have the same value.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964