Comparing objects

I’m looking for a function that compares two values. These values may or may not be objects. If they happen to be objects, I expect this function to verify that both objects have the same number of properties and that each property is contained in both. Lastly the function calls itself to evaluate each pair of properties. If they hold different values the function should return false.

let obj1 = {
	a: 1,
	b: "2",
	c: { d: 2 }
};

let obj2 = {
	a: 1,
	b: "2",
	c: { d: 2 }
};

let obj3 = {
	a: 0,
	b: "2",
	c: { d: 2 }
};

let obj4 = {
	a: 0,
	b: "2",
	c: { 
		d: 2,
		e: { f: "A" }
	}
};

function deepEqual(a, b) {
	if (typeof a == 'object' && a != null && typeof b == 'object' && b != null) {
		if (Object.keys(a).length == Object.keys(b).length) {
			for (let i = 0; i < Object.keys(a).length; i += 1) {
				if (Object.keys(b).includes(Object.keys(a)[i])) {
					console.log(Object.keys(a)[i] + ": " + a[Object.keys(a)[i]] + ", " + Object.keys(a)[i] + ": " + b[Object.keys(b)[i]]);
					deepEqual(a[Object.keys(a)[i]], b[Object.keys(a)[i]]);
				} else {
					return false;
				}
			}
		} else {
			return false;
		}
	} else if (a === b) {
		return true;
	} else {
		return false;
	}
}

Calling deepEqual with any pair of aforementioned objects doesn’t have the expected result. For starters the function returns undefined and never seems to reach the majority of the if (...) else blocks. I’m not looking for a solution but perhaps a hint that might indicate what went wrong.

What works:

Calling deepEqual on arbitrary values.

deepEqual(3, 4)
false
deepEqual(3, 3)
true

Recursion works too. If I pass deepEqual objects containing nested objects, console.log outputs their respective values.

deepEqual(obj1, obj2)
a: 1, a: 1
b: 2, b: 2
c: [object Object], c: [object Object]
d: 2, d: 2

Do you want to know whats wrong with your function? Or just want the functionality? If the latter, lodash has an isEqual() you can use.

Yeah, I’m not sure why it returns undefined instead of either true or false after looping over an object’s properties. I’m in the process of learning so I figure it’s best for me if I wrote my own stuff. Actually this is an exercise in Eloquent Javascript and despite there being solutions online, I won’t be able to sleep at night if I cheat. I already feel guilty asking for assistance online lol.

If you’d like a hint, look through all your if-else blocks and figure out which one isn’t returning anything. Then you’ll know where your undefined is coming from :wink:

2 Likes

Fixed it, thanks. Turns out I don’t know what I’m doing. Back to the drawing board lol

1 Like