Concepts of Object — Part 2

📄 Table of Contents

  • Equality on Objects?

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ ✦ ✦ ✦ ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Equality on objects

Two objects having the same properties and storing the same values are not equal.

{ char: 'A'} !== { char: 'A'}

Detecting duplicates in arrays of objects

Let’s try out.

const arr = [{char: 'A'}, {char: 'A'}];
const set = new Set(arr);const hasDuplicates = set.size < arr.length;

It doesn’t work. As already said two objects storing the same values are not equal.

What can we do then?

We can, for example, transform an object into a JSON string. Two objects with the same properties and storing the same values will produce the same JSON string. Check how we can do that using the JSON.stringify function.

const obj1 = { char: 'A' };
const obj2 = { char: 'A' };const jsonObj1 = JSON.stringify(obj1);
const jsonObj2 = JSON.stringify(obj2);
//{"char":"A"}console.log(obj1 === obj2);
console.log(jsonObj1 === jsonObj2);

Now let’s use the JSON.stringify function together with the Set collection. Instead of creating a Set of objects, we can create a Set of JSON strings.

How can we do this transformation from an array of objects to an array of JSON strings?

The map array method converts an array of values into a new array using a mapping function.

What is the mapping function in our case?

That’s right. The mapping function, in this case, is the JSON.stringify. Let’s pass it to the map method and check the result.

const arr = [{char: 'A'}, {char: 'A'}];
const jsonArr =;console.log(jsonArr);

Here is the code for detecting duplicates in an array of objects.

const arr = [{char: 'A'}, {char: 'A'}];
const set = new Set(;const hasDuplicates = set.size < arr.length;

What if we don’t want to compare all the properties of an object to find duplicates. What if we just need to compare the id property for example.

OK. This is even simpler than what we have already done. Instead of creating a new Set of objects, we create a new Set of ids. This set will contain only the unique ids.

Who can we convert a list of objects into a list of ids?

Yes, simply by using the map array method.

const arr = [
{id: 1, name: 'Joker'},
{id: 2, name: 'Bane'},
{id: 1, name: 'Joker' }
];const ids = =>;
//[1, 2, 1]

Below is the logic checking for duplicates.

const set = new Set(ids);const hasDuplicates = set.size < arr.length;



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Anil Kumar

Anil Kumar


Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.