Tutorialspoint
Problem
Solution
Submissions

Object Deep Equal Comparison

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a JavaScript function to perform deep equality comparison between two objects without using any built-in comparison methods. The function should return true if both objects have the same structure and values at all nested levels, and false otherwise. It should handle nested objects, arrays, and primitive values.

Example 1
  • Input: obj1 = {a: 1, b: {c: 2, d: [3, 4]}}, obj2 = {a: 1, b: {c: 2, d: [3, 4]}}
  • Output: true
  • Explanation:
    • Both objects have the same top-level keys (a, b).
    • The value of key 'a' is 1 in both objects.
    • The value of key 'b' is an object in both cases.
    • The nested object has keys 'c' and 'd' with identical values.
    • The array [3, 4] is identical in both objects.
Example 2
  • Input: obj1 = {a: 1, b: {c: 2}}, obj2 = {a: 1, b: {c: 3}}
  • Output: false
  • Explanation:
    • Both objects have the same structure with keys 'a' and 'b'.
    • The value of key 'a' is 1 in both objects (matching).
    • The value of key 'b' is an object in both cases.
    • The nested object has key 'c' but with different values (2 vs 3).
    • Since the values don't match, the objects are not deeply equal.
Constraints
  • Objects can contain nested objects, arrays, and primitive values
  • The comparison should be deep (recursive)
  • You cannot use JSON.stringify() or any built-in deep comparison methods
  • Handle null and undefined values properly
  • Time Complexity: O(n) where n is the total number of properties
  • Space Complexity: O(d) where d is the maximum depth of nesting
ArraysRecursionAmazonFacebook
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use recursion to handle nested objects and arrays
  • Check if both values are objects before comparing their properties
  • Compare the number of keys/properties in both objects
  • Handle special cases like null, undefined, and arrays
  • Use typeof operator to check data types before comparison

Steps to solve by this approach:

 Step 1: Check if both objects are the same reference (===).
 Step 2: Handle null and undefined cases.
 Step 3: Check if both values are objects, if not compare directly.
 Step 4: Handle array comparison by checking if both are arrays.
 Step 5: Get all keys from both objects and compare their lengths.
 Step 6: Iterate through each key and recursively compare values.
 Step 7: Return true only if all comparisons pass.

Submitted Code :