I'd like to have a set of objects in Javascript. That is, a data structure that contains only unique objects.
Normally using properties is recommended, e.g. myset["key"] = true
. However, I need the keys to be objects. I've read that Javascript casts property names to strings, so I guess I can't use myset[myobject] = true
.
I could use an array, but I need something better than O(n) performance for adding, finding and removing items.
It needs to be able to tell objects apart by reference only, so given:
var a = {}; var b = {};
then both a
and b
should be able to be added, because they're separate objects.
Basically, I'm after something like C++'s std::set
, that can store Javascript objects. Any ideas?
A set is a collection of objects. The objects are called the elements of the set. If a set has finitely many elements, it is a finite set, otherwise it is an infinite set. If the number of elements in a set is not too many, we can just list them out.
You can create a JavaScript Set by: Passing an Array to new Set() Create a new Set and use add() to add values. Create a new Set and use add() to add variables.
In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc.
{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.
ES6 provides a native Set
:
let s = new Set(); let a = {}; let b = {}; s.add(a); console.log(s.has(a)); // true console.log(s.has(b)); // false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With