Set is adding duplicated object

Viewed 16

I'm trying create a set to insert objects avoiding duplicates.

When I do this:

const orgs = new Set();

set.add({
org_name: org.org_name,
relation_type: OrganisationRelationType.SELF,
related_org: org.org_name
});

set.add({
org_name: org.org_name,
relation_type: OrganisationRelationType.SELF,
related_org: org.org_name
});

I get the following output:

Set{
  {
    org_name: org.org_name,
    relation_type: OrganisationRelationType.SELF,
    related_org: org.org_name
  },
  {
    org_name: org.org_name,
    relation_type: OrganisationRelationType.SELF,
    related_org: org.org_name
  }
}

Instead of getting this:

Set{
  {
    org_name: org.org_name,
    relation_type: OrganisationRelationType.SELF,
    related_org: org.org_name
  }
}

How can I add to this Set avoiding duplicates in an efficient way?

1 Answers

In order to avoid duplications in Set you should take into account Set equality algorithm

Please be aware that two literal objects, even if they have same values, are not equal:

{ a: 42 } === { a: 42 } // false

Because references are different. However, in case of using references instead of literal objects, such equality will be true:

const foo = { a: 42 }

foo === foo // true

See this example:

const orgs = new Set();

const obj = {
    org_name: 1,
    relation_type: 2,
    related_org: 3
}

orgs.add(obj);

orgs.add(obj);

orgs.values() // 1

If two non primitive values in a set have same reference, second value will not be added

Related