Home > Blockchain >  Spreading elements with no duplicates in Javascript
Spreading elements with no duplicates in Javascript

Time:11-18

I am looking for the way to remove duplicates. I found a common way is to create a Set and then spread into a new Array.

How could I Set to acomplish this purpose? For instance, I have the following code:

const tmp1=[];
const tmp2=[{
    guid:"e695d848-7188-4741-9c95-44bec634940f",
    name: "Spreading.pdf",
    code: "G1"
  }];
const tmp = [...new Set([...tmp1],[...tmp2])]; //This should remove duplicates, but gets empty array
const x = [...tmp1, ...tmp2]; // This would keep duplicates

The issue is that because tmp1 is an empty array, then I am getting empty result. However, if I do the following, then getting correct result:

const tmp = [...new Set(...tmp1,[...tmp2])];

I think something is missing in here.

This is an example of duplicated entries where Set is working like a charm just keeping one record:

const tmp1=[{
    guid:"e695d848-7188-4741-9c95-44bec634940f",
    name: "Spreading.pdf",
    code: "G1"
  }];
const tmp2=[{
    guid:"e695d848-7188-4741-9c95-44bec634940f",
    name: "Spreading.pdf",
    code: "G1"
  }];
const tmp = [...new Set([...tmp1],[...tmp2])];

This was the original idea, but how about if one of the lists is empty. Then, I am getting an empty array if this occurs.

Thank you

CodePudding user response:

Set should take 1 argument but it's taking 2, merge them into one:

const tmp = [...new Set([...tmp1, ...tmp2])]; 

Note: that this method won't remove duplicates because you are passing an object to the set and not a reference for it, in this case, you can do this instead:

const tmp1 = [];
const tmp2 = [{
  guid: "e695d848-7188-4741-9c95-44bec634940f",
  name: "Spreading.pdf",
  code: "G1"
},
{
  guid: "e695d848-7188-4741-9c95-44bec634940f",
  name: "Spreading.pdf",
  code: "G1"
}
];

// pass a special unique key that differs object from each other to item, in this case i passed guid
const tmp = [...new Map([...tmp1, ...tmp2].map(item => [item['guid'], item])).values()]

CodePudding user response:

Just to explain why this example seemingly work:

const tmp1=[{
    guid:"e695d848-7188-4741-9c95-44bec634940f",
    name: "Spreading.pdf",
    code: "G1"
  }];
const tmp2=[{
    guid:"e695d848-7188-4741-9c95-44bec634940f",
    name: "Spreading.pdf",
    code: "G1"
  }];
const tmp = [...new Set([...tmp1],[...tmp2])];

It results in one object because Set() only take one iterable object, so it takes the first one.

If const tmp2=[1, 2, 3] in the above example, tmp will still result in the one object in tmp1.

More about Set()

  • Related