James
James

Reputation: 127

Javascript compare value in object

The deepEqual function is supposed to take in 2 values in see if they are exactly the same. The results for the first and second test come back as expected. Is there perhaps something wrong with the way I'm incorporating the recursive call?

function deepEqual(obj1, obj2) {
  if (typeof obj1 == 'object' && typeof obj1 !== null && typeof obj2 == 'object' && typeof obj2 !== null) {
    if (obj1.length != obj2.length) {return false;}
    for (var prop in obj1) {
      if (typeof obj1[prop] == 'object') {deepEqual(obj1[prop], obj2[prop]);}
      if (obj1[prop] != obj2[prop]) {return false;}
    }
    return true;
  } else if (obj1 === obj2) {return true;}
  else {return false;}
}

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

Upvotes: 0

Views: 88

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075885

Is there perhaps something wrong with the way I'm incorporating the recursive call?

Yes, you're throwing away its return value. You should be checking its return value and, if it's false, returning false early.

if (typeof obj1[prop] == 'object') {
    if (!deepEqual(obj1[prop], obj2[prop])) {
        return false;
    }
}

Side note: There are several other issues in that code. I'm not going to get into a full review of it, but for instance, the if following the line above testing obj1[prop] to see if it's an object really should be else if, e.g.:

if (typeof obj1[prop] == 'object') {
    if (!deepEqual(obj1[prop], obj2[prop])) {
        return false;
    }
} else if (obj1[prop] != obj2[prop]) {
//^^^^------------------------------------------ here
    return false;
}

Upvotes: 6

Related Questions