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

const isEqual = (a, b) => {
if (a === b) return true;
if (a === null || b === null) return false;
if (typeof a !== 'object' || typeof b !== 'object') return false;
if (Object.keys(a).length !== Object.keys(b).length) return false;
return Object.keys(a).every(key => isEqual(a[key], b[key]));
};

Approach 3: Using lodash isEqual

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

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.