That's because indexOf
uses strict comparison (===
) so even [{a:1}].indexOf({a:1})
returns -1
.
Comparing strings is a bad idea (because toString
returns [Object object]
by default). Even comparing JSON strings is a bad idea because JSON.stringify({b:1,a:1}) !== JSON.stringify({a:1,b:1})
although the objects are obviously equal.
If you'd be willing to pull a new library to your project, you could use lodash with its _.isEqual
and _.find
functions. Note that you don't have to pull whole lodash if you don't want to - you can use the lodash.isequal
npm package (and there is a separate package for every other function in lodash, too).
Alternatively, you could write a recursive function to compare them. The function would iterate through all the keys in the objects, and if the values are both objects, it should recurse. But this way, imho, makes sense only as a programming exercise (still, a good one).
See also this great answer for more details about comparing objects in JS (note how big the code is! That's why you probably don't want to implement it yourself).