Compare two objects are same or not in JavaScript.
Tags: webdev, javascript, beginners, programming
Published: 2024-03-24 20:34:37

Object is a hash data-structure in javascript used to store data in format of key-values. 
In program sometime we need to compare two objects are equal or not. But wait here is a catch you can't compare two object directly like below code.

```js
let person1 = {
  name: "shakil",
  age: 22,
};
let person2 = {
  name: "shakil",
  age: 22,
};

console.log(person1 == person2); // false
console.log(person1 === person2); // false
```
Why they return false? Because object compare by references by default instead of internal value. Then how to compare?

There are several way to compare

<u>**Way 1: JSON.stringify()**</u>
JSON.stringify() method convert any object into string format. After converting into string we can compare them.


```js
const compareObjects = (obj1, obj2) => {
  return (
    JSON.stringify(Object.entries(obj1).sort()) ===
    JSON.stringify(Object.entries(obj2).sort())
  );
};

let person1 = {
  name: "shakil",
  age: 22,
};
let person2 = {
  name: "shakil",
  age: 22,
};

console.log(compareObjects(person1, person2)); // true
```
**Explanation:** I created an function that take two arguments and converted each of them into Object.entries which return array of [key, value] array. And sort them then it convert into JSON string and just comparing. Note that this method have some limitations.
Reason of sorting is object keys order are not fixed so if we don't sort them there have a risk to return wrong result.

<u>**Way 2: _lodash**</u>
Lodash modern JavaScript utility library it have a method named **isEqual** which performs deep comparison between two values that can be any data types. 

```js
import _ from "lodash";

let person1 = {
  name: "shakil",
  age: 22,
};
let person2 = {
  name: "shakil",
  age: 22,
};

console.log(_.isEqual(person1, person2)); // true
```

<u>**Way 3: Custom logic**</u>
In this way we can manually check two object by converting them in arrays and sort them. After sorting them we can manually compare each elements in objects. If all element match then they are same (by their properties and values, not by their references) else they are not same. Simple logic

```js
const isObject = (obj) => {
  // confirm that it is an object or not
  return typeof obj === "object" && obj !== null;
};
```
```js
const compareObjects = (obj1, obj2) => {
  /* Step - 1: */
  if (!isObject(obj1) || !isObject(obj2)) return false;

  /* Step - 2: */
  // converting them into array that contain keys of objects
  const obj1Keys = Object.keys(obj1),
    obj2Keys = Object.keys(obj2);

  /* Step - 3: */
  // if number of keys are not same then we can say they are not same
  if (obj1Keys.length !== obj2Keys.length) return false;

  /* Step - 4: */
  for (const key of obj1Keys) {
     if (obj1[key] !== obj2[key] && !isNaN(obj1[key]) && !isNaN(obj2[key])) {
      return false;
    }
  }
  return true;
};
```
```js
let person1 = {
  name: "shakil",
  age: 22,
};
let person2 = {
  age: 22,
  name: "shakil",
};

compareObjects(person1, person2); // true
```

**Explanation:**

**Step 1:** First we are checking that are they object. If any of them are not an object then return false, they can't be same.

**Step 2:** Convert each of the object into array which contain their keys.

**Step 3:** Now if number of keys in both are not same then they are not same.

**Step 4:** Traverse through each key and compare its corresponding value. If any of the values are not the same, return false. However, when encountering NaN (Not a Number), remember that NaN === NaN evaluates to false, which is an exception. Therefore, if both values are NaN, consider them equal and continue traversal. After traversing all keys and values, if no inequality is found, return true, indicating that all values are the same.

Why <code>NaN===NaN // false </code> I will discuss in another blog.


Thanks for reading.