When you write {a: 'a', b: 'b'}
, you are creating a new object in JavaScript. When you write it again, you create another object, although both objects contains the same values. When you attribute it to variables, the variables just contains references ("pointers") for each object. When you write
var test = {a: 'a', b: 'b'};
var test2 = {a: 'a', b: 'b'};
You got two variables pointing to two objects:

When you compare the two variables, you just compare the pointers. Since the two objects are different, the pointers are different and the result of the comparison is false
. OTOH, if you have done the code below
var test = {a: 'a', b: 'b'};
var test2 = test;
the result is that test
and test2
point to the same object and are equal.

(More about references on Wikipedia. It would be good to read about pointers too).
What you want to do use a deep comparison in the $.inArray()
function. If your objective would be to just compare values, I would recommend you to use the Underscore.js isEqual()
function. Since it is not the case, and $.inArray()
does not accept a comparator as parameter, I bet you will have to implement it manually:
function inArray(element, array) {
for (var key in array) {
if (_.isEqual(element, array[key])) {
return true;
}
}
return false;
}
EDIT: well, it would be awesome if our function does receive the comparator as a parameter!
function inArray(element, array, cmp) {
if (typeof cmp != "function") {
cmp = function (o1, o2) {
return o1 == o2;
};
}
for (var key in array) {
if (cmp(element, array[key])) {
return true;
}
}
return false;
}
Testing in Node.js:
> inArray(test2, a)
false
> inArray(test2, a, function(o1, o2){return o1 === o2;})
false
> inArray(test2, a, _.isEqual)
true
Of course, this brings more complexity for your specific problem, so you do not need to use it. However, I think it may be valid to register the idea :)