Question 11
Question
How would you determine if two objects are structurally equal (e.g., object shapes)?
Answer
Determining structural equality means checking if two objects have the same properties and values, regardless of their order or nesting depth.
Here's a function to achieve that:
Explanation:
Base Case: If either input isn't an object, we directly compare their values (since primitives are compared by value). 2. Property Counts: We ensure both objects have the same number of properties using
Object.keys()
. 3. Recursive Comparison:For each matching property key:
Recursively call
areStructurallyEqual()
to compare nested objects.If any recursive comparison returns
false
, we know they're not structurally equal, so returnfalse
.
Structural Equality: Only if all property comparisons succeed, do we return
true
, indicating structural equality.
Last updated