Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 260
garrettmaring Avatar asked Mar 30 '26 20:03

garrettmaring


1 Answers

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;
}
like image 126
Bergi Avatar answered Apr 02 '26 09:04

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!