JS: Test Object Equality 🚀

By Xah Lee. Date: . Last updated: .

Here's a function to compare equality of objects by comparing every element.

This is most useful for data objects. (such as comparing JSON objects with arbitrarily nested object or array.)

/*
xah_is_obj_equal(xx, yy)
Return true if every enumerable property keys and values are equal. (symbol keys are ignored), nested objects are compared the same way.
Order of properties does not matter.
Argument may be Object, true array, Array-like objects.

* For true arrays, index are considered as key. (and order matters.)
* Array-like objects are considered the same as object.
* Map and Set object are not treated in a special way here. You should not use this function to compare them.
* If one of the argument is not object type, result is same as triple equal operator.

URL http://xahlee.info/js/js_test_object_equality.html
Version 2022-10-13 2022-10-14
 */
const xah_is_obj_equal = ((xx, yy) => {
  if (xx === yy) return true;
  if ((typeof xx !== "object") || (typeof yy !== "object")) {
    return xx === yy;
  }
  if (Array.isArray(xx) && Array.isArray(yy)) {
    if (xx.length !== yy.length) {
      return false;
    } else {
      return xx.every((v1, ii) => xah_is_obj_equal(v1, yy[ii]));
    }
  } else {
    const keys1 =
      ((Array.isArray(xx)) ? Object.keys(xx) : Object.keys(xx).sort());
    const keys2 =
      ((Array.isArray(yy)) ? Object.keys(yy) : Object.keys(yy).sort());
    if (keys1.length !== keys2.length) return false;
    if (!keys1.every((k, i) => (k === keys2[i]))) return false;
    return keys1.every((kk) => xah_is_obj_equal(xx[kk], yy[kk]));
  }
});

// ssss---------------------------------------------------
// test

// compare array
console.log(xah_is_obj_equal([3, [3, 4]], [3, [3, 4]]));

// compare object
console.log(
  xah_is_obj_equal(
    { "a": 1, "b": { "a": 1, "b": 2 } },
    { "a": 1, "b": { "a": 1, "b": 2 } },
  ),
);

// arbitrarily nested object/array
console.log(
  xah_is_obj_equal(
    { "a": 1, "b": { "a": 1, "b": [3, [{ "a": 1, "b": [3, [3, 4]] }, 4]] } },
    { "a": 1, "b": { "a": 1, "b": [3, [{ "a": 1, "b": [3, [3, 4]] }, 4]] } },
  ),
);

// compare primitives
console.log(xah_is_obj_equal(3, 3));
console.log(xah_is_obj_equal(3, 3.0));
console.log(xah_is_obj_equal("x", "x"));
console.log(xah_is_obj_equal(Infinity, Infinity));
console.log(xah_is_obj_equal(3, 4) === false);

Test Object Equality by JSON String, Ordering Problem

JavaScript, Object and Inheritance

JavaScript, Boolean

BUY ΣJS JavaScript in Depth