Implement deepEqual
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Implement deepEqual(a, b). It returns true when the two values have the same structure and contents, even if they are different objects in memory, and false otherwise.
=== compares objects by reference, so two objects with the same contents are never equal with it. Tests, React's memoization and state libraries all need a structural comparison instead.
deepEqual({ a: 1, b: [1, 2] }, { a: 1, b: [1, 2] }) // true
deepEqual({ a: 1 }, { a: 1, b: 2 }) // false
deepEqual([1, 2, 3], [1, 2, 3]) // true
deepEqual([1, 2], { 0: 1, 1: 2 }) // false
deepEqual(NaN, NaN) // trueRequirements
- Primitives are equal when
===says so, with one exception:NaNequalsNaN. - Arrays are equal when they have the same length and their items are deeply equal, in order.
- Plain objects are equal when they have the same own keys (in any order) and the values under each key are deeply equal.
- An array never equals a plain object, and
nullonly equalsnull. { a: undefined }and{ b: undefined }are not equal: they have different keys.
Note
You don't need to handle Date, Map, Set, class instances or circular references. Inputs are made of primitives, plain objects and arrays.
Approach
Check the cheap cases first, then recurse:
- Same value: if
a === b, returntrue. This covers equal primitives and the same object passed twice. NaN:NaN !== NaN, so checkNumber.isNaN(a) && Number.isNaN(b)explicitly.- Not both objects: if either is not an object, or is
null(typeof nullis'object'), the values differ. - Array vs. object: if one is an array and the other isn't, return
false. - Keys: compare
Object.keys(a).lengthwithObject.keys(b).length, then check every key ofaexists inb(withObject.hasOwn) and that the values are deeply equal.
Arrays need no special loop: Object.keys of an array is its indices, so step 5 compares them item by item, and the length check catches arrays of different sizes.
The undefined trap
Comparing only a[key] with b[key] treats { a: undefined } and { b: undefined } as equal, because b.a is also undefined. Checking Object.hasOwn(b, key) catches the missing key.
Complexity
O(n) time, where n is the total number of values in both structures, since each one is visited once. The recursion depth is the nesting depth of the input.
Follow-ups interviewers ask
- Circular references: keep a
Mapof pairs already being compared, and treat a pair seen again as equal, or the recursion never ends. - More types: compare
Dates withgetTime(),RegExps withsourceandflags, andMaps andSets by their entries. - Prototypes: should an instance of a class equal a plain object with the same fields? Comparing
Object.getPrototypeOfmakes the answer no. - Shallow equal: the one-level version React uses for
memoandPureComponentprops.
Reference solution
/**
* @param {*} a
* @param {*} b
* @returns {boolean}
*/
export default function deepEqual(a, b) {
if (a === b) return true
if (Number.isNaN(a) && Number.isNaN(b)) return true
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false
if (Array.isArray(a) !== Array.isArray(b)) return false
const keysA = Object.keys(a)
const keysB = Object.keys(b)
if (keysA.length !== keysB.length) return false
return keysA.every((key) => Object.hasOwn(b, key) && deepEqual(a[key], b[key]))
}export default function deepEqual(a: unknown, b: unknown): boolean {
if (a === b) return true
if (Number.isNaN(a) && Number.isNaN(b)) return true
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false
if (Array.isArray(a) !== Array.isArray(b)) return false
const objectA = a as Record<string, unknown>
const objectB = b as Record<string, unknown>
const keysA = Object.keys(objectA)
const keysB = Object.keys(objectB)
if (keysA.length !== keysB.length) return false
return keysA.every((key) => Object.hasOwn(objectB, key) && deepEqual(objectA[key], objectB[key]))
}