Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two objects properties but not working propery

Tags:

javascript

Here is my code. I know it's not entirely strict but please shed some light on why the let...in does not work properly here.

const object1 = {here: 1, object: 3};
const obj = {here: 1, object: 2};

function comp(a, b) {
  if (typeof a == typeof b) {
    let arra = Object.keys(a);
    let arrb = Object.keys(b);
    for (let key in arra){
      if (a[key] == b[key]) return true
    }
        return false
  }
}

console.log(comp(obj, object1))

The above prints true but it is supposed to print false

like image 230
lalaland4545 Avatar asked Mar 14 '26 02:03

lalaland4545


1 Answers

You're getting true because you return true in your for loop whenever a key value from one object equals the key-value pair of another object. So when your code sees the here property, it will return true, thus stopping your function from running any further code.

You need to remove this check, and only return false in your for loop, such that your for loop will only complete if it never returns (ie: all key-value pairs are equal).

Moreover, the for..in loop will loop over the keys in an object, so, there is no need to get the keys of your objects (using Object.keys) into an array (as then you'll be looping over the keys of an array (ie: the indexes)).

However, with that being said, you can use Object.keys to help with another issue. You can use it to get the number of properties in both objects, as you know the two objects are not the same if they don't have the same number of properties in them

See example below:

const object1 = {
  here: 1,
  object: 3
};
const obj = {
  here: 1,
  object: 3
};

function comp(a, b) {
  if (typeof a == typeof b) {
    if(Object.keys(a).length !== Object.keys(b).length) {
      return false; // return false (stop fruther code execution)
    }
  
    for (let key in a) { // loop through the properties of larger object (here I've chosen 'a') - no need for Object.keys
      if (a[key] != b[key]) 
        return false; // return false (stops any further code executing)
    }
    return true; // we only reach this point if the for loop never returned false
  }
  return false; // we reach this point when the two types don't match, and so we can say they're not equal
}

console.log(comp(obj, object1))
like image 95
Nick Parsons Avatar answered Mar 15 '26 16:03

Nick Parsons



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!