4

I have this:

var g = [{a:'a'},{a:'2'},{a:'3'}]
var c = [{a:'4'},{a:'2'},{a:'5'}]

The following statement:

g[1] == c[1]

Returns false, even though the objects look the same. Is there any way I can compare them literally so it will return me true instead of false?

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
simmu
  • 83
  • 1
  • 5
  • 1
    In javascript, `({a:1}) == ({a:1})`, and even `[1] == [1]` return false. The == operator doesn't try to automatically implement structural equality of objects. – millimoose Oct 03 '11 at 21:19
  • It depends on structure of your objects. Are they all in the same structure. And more, depends on how you want to compare them. Compare all the childs' value, one by one, or whatever ? – vantrung -cuncon Oct 03 '11 at 21:22

4 Answers4

6

You could encode them as JSON:

JSON.stringify(g[1]) == JSON.stringify(c[1])

You might also be interested in the answers to this related question on identifying duplicate Javascript objects.

For a more complex option, you might look at the annotated source code for Underscore's _.isEqual() function (or just use the library).

Community
  • 1
  • 1
nrabinowitz
  • 55,314
  • 10
  • 149
  • 165
  • Very nice! Didn't think of that. – Eric Oct 03 '11 at 21:22
  • Could we use some clever version of [filter](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter)? – mplungjan Oct 03 '11 at 21:25
  • Thank you, never thought of that. This will be handy. Initially I was trying to use _.unique to filter out existing obj but from what I read here, this method will not work. I'll figure out another way. Thank you all for the explanation. – simmu Oct 03 '11 at 21:29
1

The == operator checks for reference equality. The only way to do what you want would be a memberwise equality test on the objects.

This ought to work:

function memberwiseEqual(a, b) {
    if(a instanceof Object && b instanceof Object) {
        for(key in a)
            if(memberwiseEqual(a[key], b[key]))
                return true;
        return false;
    }
    else
        return a == b;
}

Be wary of cases like these:

var a = {};
a.inner = a; //recursive structure!
Eric
  • 95,302
  • 53
  • 242
  • 374
0

here you compare the reference in the memory ,not its value try this and you will get true :

g[1]['a'] === c[1]['a']
shox
  • 1,150
  • 5
  • 18
  • 32
0

In JavaScript variables which are objects (including arrays) are actually references to the collection. So when you write var x = { a: 2 } and var y = { a: 2 } then x and y become references to two different objects. So x will not equal y. But, if you did y = x then they would (because they would share the same reference). But then if you altered either object the other would be altered too.

So, when dealing with objects and arrays, by saying == you are checking if the two references are the same. In this case they are not.

Marshall
  • 4,716
  • 1
  • 19
  • 14