Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Javascript Set not do unique objects?

Tags:

javascript

Sets are supposed to contain unique objects, but it doesn't work for objects in javascript.

var set = new Set() <- undefined set.add({name:'a', value: 'b'}) <- Set {Object {name: "a", value: "b"}} set.add({name:'a', value: 'b'}) <- Set {Object {name: "a", value: "b"}, Object {name: "a", value: "b"}} 

It works for primitives

var b = new Set() <- undefined b.add(1) <- Set {1} b.add(2) <- Set {1, 2} b.add(1) <- Set {1, 2} 

So how do I get it to work with objects? I get the fact that they are different objects with the same values, but I'm looking for like a deep unique set.

EDIT:

Here's what I'm actually doing

    var m = await(M.find({c: cID}).populate('p')) //database call     var p = new Set();     m.forEach(function(sm){         p.add(sm.p)     }) 

This is to get a unique list of sm.p

like image 649
Matt Westlake Avatar asked Dec 31 '16 01:12

Matt Westlake


People also ask

Does JavaScript Set work for objects?

Sets are supposed to contain unique objects, but it doesn't work for objects in javascript.

Is Set unique JavaScript?

Set objects are collections of values. A value in the Set may only occur once; it is unique in the Set 's collection.

Does Set work on objects?

If you have an array of objects instead and need to find the unique values of one object property across all of those objects, you can do it with Set .


1 Answers

well, if you are looking for a deep unique set, you can make a deep set by youself, by extending the original 'Set', like this:

function DeepSet() {     // } DeepSet.prototype = Object.create(Set.prototype); DeepSet.prototype.constructor = DeepSet; DeepSet.prototype.add = function(o) {     for (let i of this)         if (deepCompare(o, i))             throw "Already existed";     Set.prototype.add.call(this, o); }; 
like image 72
Joe Yichong Avatar answered Oct 08 '22 09:10

Joe Yichong