Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set of objects in javascript

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?

like image 205
AshleysBrain Avatar asked Apr 14 '11 00:04

AshleysBrain


People also ask

What is a set of object?

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.

Can we create set of objects in JavaScript?

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.

What are the objects of JavaScript?

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.

What is {} and [] in JavaScript?

{} 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.


1 Answers

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
like image 181
Ry- Avatar answered Sep 23 '22 05:09

Ry-