I want to have unique array of objects. So if I add an object, any objects which have same values won’t be added twice.
So I try use Set() data structure.
Adding Object directly to Set()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
const d1 = {ID: 1, distance: 2} const d2 = {ID: 1, distance: 3} const d3 = {ID: 1, distance: 2} const set1 = new Set() set1.add(d1) set1.add(d2) set1.add(d3) console.log("size set1: ", set1.size) for(const item of set1.values()){ console.log("item ", item) } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 |
[LOG]: "size set1: ", 3 [LOG]: "item ", { "ID": 1, "distance": 2 } [LOG]: "item ", { "ID": 1, "distance": 3 } [LOG]: "item ", { "ID": 1, "distance": 2 |
Conclusion:
As you can see, the Set result is 3. It should be 2. So it doesn’t work
Adding a stringify Object to Set()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const d1 = {ID: 1, distance: 2} const d2 = {ID: 1, distance: 3} const d3 = {ID: 1, distance: 2} const set2 = new Set() set2.add(JSON.stringify(d1)) set2.add(JSON.stringify(d2)) set2.add(JSON.stringify(d3)) console.log("size set 2: ", set2.size) for(const item of set2.values()){ console.log("item ", item) } |
Output:
1 2 3 |
[LOG]: "size set 2: ", 2 [LOG]: "item ", "{"ID":1,"distance":2}" [LOG]: "item ", "{"ID":1,"distance":3}" |
Conclusion:
The Set size is 2 with no duplicate values.
Overall Conclusion
So you can use Set but first stringifiy the objects than convert back the string to object by using JSON.parse() function
You can try thecoding yourself here:
Typescript Playground