Skip to content

Instantly share code, notes, and snippets.

@jonurry
Last active March 22, 2022 20:31
Show Gist options
  • Save jonurry/d92265f98b0322a5e994894f076c2b2c to your computer and use it in GitHub Desktop.
Save jonurry/d92265f98b0322a5e994894f076c2b2c to your computer and use it in GitHub Desktop.
4.4 Deep Comparison (Eloquent JavaScript Solutions)
function deepEqual(a, b) {
if (a === b) {
// items are identical
return true;
} else if (typeof a === 'object' && a !== null && typeof b === 'object' && b !== null) {
// items are objects - do a deep property value compare
// join keys from both objects together in one array
let keys = Object.keys(a).concat(Object.keys(b));
// filter out duplicate keys
keys = keys.filter(
function (value, index, self) {
return self.indexOf(value) === index;
}
);
for (p of keys) {
if (typeof a[p] === 'object' && typeof b[p] === 'object') {
if (deepEqual(a[p], b[p]) === false) {
return false;
}
} else if (a[p] !== b[p]) {
return false;
}
}
return true;
} else {
return false;
}
}
// Tests
let obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true
console.log(deepEqual(obj, {here: {is: "an"}, object: 0}));
// → false
console.log(deepEqual(obj, {here: {is: "another"}, object: 2}));
// → false
console.log(deepEqual(obj, {here: {isnt: "an"}, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an", deep: {poop: null, value: -1}}, object: 2}));
// → false
let json = '{"candidate": "Jon Urry", "job": "Junior Full-Stack JavaScript Developer", "portfolio": "jon.urry.me", "skills": ["HTML", "CSS", "JavaScript", "ES6", "Node", "React", "Vue", "Git", "XML", "UX", "Responsive Design", "Design Patterns", "TDD", "Chrome Inspector", "Agile", "SEO", "Analytics", "WordPress", "Databases"], "contact": [{"email": "mailto:jon@urry.me"}, {"github": "github.com/jonurry"}, {"linkedin": "linkedin.com/in/jonurry"}, {"mobile": "tel:+44-7986-371-299"}, {"skype": "skype:jonurry"}, {"twitter": "twitter.com/jonurry"}]}';
let json2 = '{"candidate": "Jon Urry", "job": "Junior Full-Stack JavaScript Developer", "portfolio": "jon.urry.me", "skills": ["HTML", "CSS", "JavaScript", "ES6", "Node", "React", "Vue", "Git", "XML", "UX", "Responsive Design", "Design Patterns", "TDD", "Chrome Inspector", "Agile", "SEO", "Analytics", "WordPress", "Databases2"], "contact": [{"email": "mailto:jon@urry.me"}, {"github": "github.com/jonurry"}, {"linkedin": "linkedin.com/in/jonurry"}, {"mobile": "tel:+44-7986-371-299"}, {"skype": "skype:jonurry"}, {"twitter2": "twitter.com/jonurry2"}]}';
let jsonObj = JSON.parse(json);
let jsonObjCopy = JSON.parse(JSON.stringify(jsonObj));
let jsonObj2 = JSON.parse(json2);
console.log(jsonObj);
console.log(deepEqual(jsonObj, jsonObj));
// → true
console.log(deepEqual(jsonObj, jsonObjCopy));
// → true
console.log(deepEqual(jsonObj, jsonObj2));
// → false
console.log(deepEqual(null, obj));
// → false
console.log(deepEqual(obj, null));
// → false
console.log(deepEqual(null, null));
// → true
@jonurry
Copy link
Author

jonurry commented Feb 8, 2018

4.4 Deep Comparison

The == operator compares objects by identity. But sometimes, you would prefer to compare the values of their actual properties.

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.

To find out whether to compare two things by identity (use the === operator for that) or by looking at their properties, you can use the typeof operator. If it produces "object" for both values, you should do a deep comparison. But you have to take one silly exception into account: by a historical accident, typeof null also produces "object".

The Object.keys function will be useful when you need to go over the properties of objects to compare them one by one.

@jonurry
Copy link
Author

jonurry commented Feb 15, 2018

Hints

Your test for whether you are dealing with a real object will look something like typeof x == "object" && x != null. Be careful to compare properties only when both arguments are objects. In all other cases, you can just immediately return the result of applying ===.

Use Object.keys to go over the properties. You need to test whether both objects have the same set of property names and whether those properties have identical values. One way to do that is to ensure that both objects have the same number of properties (the lengths of the property lists are the same). And then, when looping over one of the object’s properties in order to compare them, always first make sure the other actually has a property by that name. If they have the same number of properties, and all properties in one also exist in the other, they have the same set of property names.

Returning the correct value from the function is best done by immediately returning false when a mismatch is found and return true at the end of the function.

@CryptoCoolby
Copy link

CryptoCoolby commented Jul 19, 2018

Hey, I found a bug in the code.

deepEqual({here: "is", here: "is"}, {here: "is"})
// returns true

@nirat25
Copy link

nirat25 commented Dec 18, 2018

Hi I came up with the following solution but it is not working for second and third tests as expected, any insights would be appreciated:

// Your code here.
function deepEqual(val1, val2){

if ((val1 != null && typeof val1 == "object") && (val2 != null && typeof val2 == "object")){

if(Object.keys(val1).length != Object.keys(val2).length){
  return false;
} else {
  for (let props of Object.keys(val1)){
    
  	if(!Object.keys(val2).includes(props)){
      return false;
      break;
    } 
    
    if(val2[props] != val1[props]){
      return false;
      break;
    }; 
    
  };
  return true;
};    

} else {
return val1 === val2;
};
};

let obj = {here: {is: "an"}, object: 2};

console.log(deepEqual(obj, obj));
// → true
//console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true

@buttercubz
Copy link

if (a === b) {
    // items are identical
    return true;
  }

you can add this line

if (a === b) {
    // items are identical
    return true && Object.is(a,b);
  }

in this way it will not evaluate as true the following expression:

deepEqual(+0, -0); // true

@rob-saunders
Copy link

Hey, I found a bug in the code.

deepEqual({here: "is", here: "is"}, {here: "is"})
// returns true

I know this comment has a couple years on it, but ....
You can't have a hash with two like key values I'm pretty sure. And knowing JavaScript being all floppy, it doesn't complain about it, it just overwrite's the previously assigned values to that key.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment