Skip to main content

Deep Equal of two objects

Given two objects, determine if they are equal.

A deep equal is a process in which the entire object is compared to another object, including all nested objects and their properties.

function deepEqual(objA, objB) {
// your code here
}

Example of usage

const a = { name: 'Tim', skills: ['JS', 'React'] };
const b = { name: 'Tim', skills: ['JS', 'React'] };

console.log(isEqual(a, b)); // true

Approach 1: Using JSON.stringify

const isEqual = (a, b) => {
return JSON.stringify(a) === JSON.stringify(b);
};

Approach 2: Using Recursion

This is the preferred approach that Interviewers are looking for. Hovewer, it's important to mention other possible approaches.

Here is the key points to consider:

  • Handle strict equality and primitive types with ===
  • Handle null and undefined
  • Handle non-object types
  • Handle different number of keys
  • Handle circular references
  • Handle Arrays with recursive element checking
  • Handle Dates objects comparison with Date.prototype.getTime
  • Handle Objects comparison with key-by-key recursive checking

Implementation:

const isEqual = (a, b) => {
// Handle strict equality and primitive types
if (a === b) return true;

// handle null and undefined
if (a === null || b === null) return false;

// handle non-object types
if (typeof a !== 'object' || typeof b !== 'object') return false;

const keysA = Object.keys(a);
const keysB = Object.keys(b);

// handle different number of keys
if (keysA.length !== keysB.length) return false;

// compare each key recursively
for (let key of keysA) {
if (!keysB.includes(key)) return false;
if (!isEqual(a[key], b[key])) return false;
}

return true;
};

Summary

  • Deep equal is a process in which the entire object is compared to another object, including all nested objects and their properties.
  • There are several approaches to implement deep equal.
    • The best approach is to use lodash isEqual.
    • The second best approach is to use recursion.
    • The worst approach is to use JSON.stringify.