vadersfather
vadersfather

Reputation: 9299

Recursive Deep Compare

For recursion practice/fun I was hoping to build a recursive function that would execute a deep compare of two unique objects. My code thus far, with pseudo-code comments.

I think my error is possibly in my understanding of delete because the recursion isn't solving a reduced size of obj1 and obj2.

function deepCompare(obj1, obj2) {
    //Base Cases
    if (obj1 === obj2) {
        return true;
    };
    if (Object.keys(obj1).length !== Object.keys(obj2).length) {
        return false;
    };

    //Getting arbitrary key of obj1
    var key = Object.keys(obj1)[0];

    //Check to see if key is in obj2
    if (obj2.hasOwnProperty(key)) {
        //Check equality of value at key
        if (obj2.key == obj1.key) {
            //Remove key/value pair from each object, recursively call
            delete obj2.key;
            delete obj1.key;
            deepCompare(obj1, obj2);
        } else {
            return false;
        }
    } else {
        return false;
    }
}

Upvotes: 3

Views: 1562

Answers (2)

Jose Ricardo Bustos M.
Jose Ricardo Bustos M.

Reputation: 8164

hope it helps

Edit, thanks @TrueBlueAussie

function deepcompare(a, b){
  if(typeof a !== typeof b) return false;
  if(typeof a !== 'object') return a === b;
  if(Object.keys(a).length != Object.keys(b).length) return false;
  for(var k in a){
    if(!(k in b)) return false;
    if(!deepcompare(a[k], b[k])) return false;
  }
  return true;
}

Upvotes: 1

Bergi
Bergi

Reputation: 664474

Your function is missing a base case for empty objects, i.e. objects that have no own keys (any more). It never really returns true (for non-identical objects).

So you'd need to do

function deepCompare(obj1, obj2) {
    //Base Cases
    if (obj1 === obj2) {
        return true;
    }
    var keys = Object.keys(obj1);
    if (keys.length !== Object.keys(obj2).length) {
        return false;
    }
    if (keys.length == 0) {
        return true;
    }
    //Getting arbitrary key of obj1
    var key = keys[0];
    …

Also, you forgot a return statement on your recursive call.

But notice that a comparison function should never ever modify the values it is trying to compare. So don't use delete, but rather use a loop over the keys.

function deepCompare(obj1, obj2) {
    if (obj1 === obj2) return true;
    if (typeof obj1 != typeof obj2) return false; // needed for structurally different objects
    if (Object(obj1) !== obj1) return false; // primitive values
    var keys = Object.keys(obj1);
    if (keys.length != Object.keys(obj2).length) return false;
    for (var i=0; i<keys.length; i++) {
        var key = keys[i];
        if (!Object.prototype.hasOwnProperty.call(obj2, key)) return false;
        if (!deepCompare(obj1[key], obj2[key])) return false;
    }
    return true;
}

Upvotes: 2

Related Questions