Exercise 13: Check if Two Objects are Equal (deep)
Problem Statement
Create a function `deepEqual(a, b)` that deeply compares if two objects are equal.
Example: deepEqual({a: 1, b: {c: 2}}, {a: 1, b: {c: 2}}) → true
Sample Output:
deepEqual({a: 1, b: {c: 2}}, {a: 1, b: {c: 2}}) => true
deepEqual({a: 1}, {a: 2}) => false
deepEqual({x: 1, y: 2}, {x: 1}) => falseSolution
const deepEqual = (a, b) => {
if (a === b) return true;
if (a == null || b == null || typeof a !== "object" || typeof b !== "object") return false;
const keysA = Object.keys(a), keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
for (const key of keysA) {
if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false;
}
return true;
};Explanation
Overall Goal:
- Deep comparison: nested objects bhi compare.
- Structure aur values dono check.
Line 1: Function header
const deepEqual = (a, b) => {
Line 2: Reference equality
if (a === b) return true;- Same reference ho to equal.
Line 3: Type/null check
if (a == null || b == null || typeof a !== "object" || typeof b !== "object") return false;- Null ya non-object ho to false.
Line 4: Get keys
const keysA = Object.keys(a), keysB = Object.keys(b);
Line 5: Length check
if (keysA.length !== keysB.length) return false;- Different number of keys → not equal.
Line 6-7: Compare each key
for (const key of keysA)→ iterate keys.!keysB.includes(key)→ key missing?!deepEqual(a[key], b[key])→ recursive comparison.
Real world:
- State comparison: React shouldComponentUpdate.
- Form validation: compare form data.
- Testing: assert object equality.