简体   繁体   中英

Spreading elements with no duplicates in Javascript

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

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()]

Just to explain why this example in the question 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM