Skip to content
Advertisement

Javascript – deepEqual Comparison

Question (From Eloquent Javascript 2nd Edition, Chapter 4, Exercise 4):

Write a function, deepEqual, that takes two values and returns true only if they are the same value or are objects with the same properties whose values are also equal when compared with a recursive call to deepEqual.

Test Cases:

JavaScript

My code:

JavaScript

I think I have the general idea down; however, like I stated in the comment, the program will not check the second property in the objects. I feel like I have a structural/logic problem and am simply using recursion in the wrong way, as I originally intended to loop through the properties, use recursion to compare the values of the first property, then continue on in the loop to the next property and compare again. Although, I’m not sure if that’s even possible?

I’ve given a good amount of thought and tried a couple different approaches, but this was the most correct answer I’ve come to so far. Any possible tips to point me in the right direction?

Advertisement

Answer

As you suspect, you’re returning the match of the first property seen. You should return false if that property doesn’t match, but keep looking otherwise.

Also, return false if there’s no prop property found on y (that is, the counts match, but not the actual properties).

If all properties have matched, return true:

JavaScript

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement