Concepts of Object — Part 2

📄 Table of Contents

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

Equality on objects

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

Detecting duplicates in arrays of objects

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

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);
//{"char":"A"}
const jsonObj2 = JSON.stringify(obj2);
//{"char":"A"}console.log(obj1 === obj2);
//false
console.log(jsonObj1 === jsonObj2);
//true

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 = arr.map(JSON.stringify);console.log(jsonArr);
//[
//"{"char":"A"}",
//"{"char":"A"}"
//]

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

const arr = [{char: 'A'}, {char: 'A'}];
const set = new Set(arr.map(JSON.stringify));const hasDuplicates = set.size < arr.length;
console.log(hasDuplicates)
//true

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 = arr.map(obj => obj.id);
console.log(ids);
//[1, 2, 1]

Below is the logic checking for duplicates.

const set = new Set(ids);const hasDuplicates = set.size < arr.length;
console.log(hasDuplicates)
//true

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