Categories
JavaScript Answers

How to compare arrays of objects in JavaScript?

Spread the love

Sometimes, we want to compare arrays of objects in JavaScript.

In this article, we’ll look at how to compare arrays of objects in JavaScript.

How to compare arrays of objects in JavaScript?

To compare arrays of objects in JavaScript, we can use some array properties and methods.

For instance, we write

const obj1 = { name: "John", age: 33 };
const obj2 = { age: 33, name: "John" };
const obj3 = { name: "John", age: 45 };

const arr1 = [obj1, obj1];
const arr2 = [obj1, obj2];
const arr3 = [obj1, obj3];

const objectsEqual = (o1, o2) =>
  typeof o1 === "object" && Object.keys(o1).length > 0
    ? Object.keys(o1).length === Object.keys(o2).length &&
      Object.keys(o1).every((p) => objectsEqual(o1[p], o2[p]))
    : o1 === o2;

const arraysEqual = (a1, a2) =>
  a1.length === a2.length && a1.every((o, idx) => objectsEqual(o, a2[idx]));

console.log(arraysEqual(arr1, arr2)); // true
console.log(arraysEqual(arr1, arr3));

to define the objectsEqual function that recursive checks if every property in objects o1 and o2 are equal.

We do this by checking if o1 is an object.

If it is, then we check if the number of properties of o1 and o2 are the same with

Object.keys(o1).length === Object.keys(o2).length

And then we use

Object.keys(o1).every((p) => objectsEqual(o1[p], o2[p]))

to check if each property is equal.

We call objectsEqual with the property p of o1 and o2 since they’re objects.

Otherwise, we compare the values directly with

o1 === o2

Then we define the arrayEqual function that checks if array a1 and a2‘s length and content are equal with

a1.length === a2.length && a1.every((o, idx) => objectsEqual(o, a2[idx]);

Conclusion

To compare arrays of objects in JavaScript, we can use some array properties and methods.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.