Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two objects to see if equal

Tags:

javascript

currently I am following a book and am severely confused and have tried understandng the following code several times. My first confusion is actually approaching the problem of comparing two objects a, and b.

 function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

var 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
like image 696
Muntasir Alam Avatar asked Jun 20 '16 19:06

Muntasir Alam


People also ask

How do you compare two objects are equal?

The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address. Syntax: public boolean equals(Object obj)

Can you compare objects with ==?

Comparing Objects ¶ When using the comparison operator ( == ), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values (values are compared with == ), and are instances of the same class.

What is the difference between == and the equal () method to compare two objects?

In simple words, == checks if both objects point to the same memory location whereas . equals() evaluates to the comparison of values in the objects. If a class does not override the equals method, then by default, it uses the equals(Object o) method of the closest parent class that has overridden this method.

Are .equals and == the same?

In java both == and equals() method is used to check the equality of two variables or objects. == is a relational operator which checks if the values of two operands are equal or not, if yes then condition becomes true. equals() is a method available in Object class and is used to compare objects for equality.

How do I compare two objects with the equals method?

To compare two objects with the equals method, follow these four steps. Open your text editor and create a new file that will contain the circle class and a main method to test two circles for equality.

What is the difference between == and equals in Java?

In Java, the == operator compares that two references are identical or not. Whereas the equals () method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity.

How to compare two objects with different memory addresses?

The two objects will be equal if they share the same memory address. The method parses a reference object as a parameter. It returns true if the objects are equal, else returns false. It is also possible that an object is equal to another given object, then the equals () method follow the equivalence relation to compare the objects.

How to compare two employee objects in Java?

Compare Two Employee Objects in java In the below program, Created two Employee objects with different values. Now, our need is to compare two objects that are the same or not. Every class in java has one parent class that is Object class and it has equals () method to compare two any objects. This program compiles and executes successfully.


2 Answers

function deepEqual(a, b) {
  if (a === b) return true;

First, we're checking if a and b are strictly equal (meaning, "referring to exactly the same thing"). Most things, such as strings and numbers, will pass this test if they are equal; objects are the exception, since two "identical" objects may not necessarily be the same object (they can just look the same).

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

Then we're saying that if either of the two is not an object, and they did not pass the last test, then they cannot be the same. Again, objects are the exception here, so the remaining code will take care of the case where a and b are both objects.

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

This code simply counts the number of properties of a.

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

This code takes every property in b, and checks that a contains the same property with the same value. If a doesn't have a property that b has, or they are different, then the two objects cannot be equal.

  return propsInA == propsInB;
}

Finally, if a and b do not have the same number of properties, then they cannot be equal. However, if they do have the same number of properties, then a and b must be equal, since a has all the properties that b has, and only those.

like image 51
Frxstrem Avatar answered Oct 17 '22 20:10

Frxstrem


I'll walk you through it.

if (a === b) return true;

We check if these are the same thing, we'll come back to here later.

if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

We check if one or neither of these things are objects are defined. We'll come back here too.

Keep these first two snippets in mind, they don't come into play until we call the function recursively.

var propsInA = 0, propsInB = 0;

These will be used to keep track of the number of properties in object A and B

for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

We have two for loops. The first one just loops through all properties in A (look up For...in syntax if you're unfamiliar), and for each it increments the variable propsInA.

The second loop does the same for B, but here it gets more complicated. First it checks if that property exists in A, or if deepequal returns true. This is where the first two snippets we examined come into play. The first snippet is used here to return true if the properties we give it are the same. The second snippet says "if we passed properties instead of functions, stop here". This is important because this function only needs to go on past here if its the initial invocation. All recursive invocations only need to use the first part. If either of these two return false, we return false to the initial invocation, because we know there was a difference between A and B.

return propsInA == propsInB;

We can't return true here, because we don't actually know if there is just less properties in B. Even though everything else appeared the same, we can't assume that they have the same amount of properties. This assures, as a final check, that we will only return true if the number of properties in A is equal to the number in B

Feel free to ask me to explain further.

like image 43
master565 Avatar answered Oct 17 '22 20:10

master565