In Eloquent JavaScript, Chapter 4, a set of values is created by creating an object and storing the values as property names, assigning arbitrary values (e.g. true) as property values. To check if the value is already contained in the set, the in
operator is used:
var set = {};
if (!'Tom' in set) {
set.Tom = true;
}
Is this idiomatic JavaScript? Wouldn't be using an array even better?
var set = [];
if (!'Tom' in set) {
set.push = 'Tom';
}
Sets in
ES6
/ES2015
:ES6
/ES2015
now has built in sets. A set is data structure which allows storage of unique values of any type, whether this are primitive values or object references. A set can be declared using theES6
built in set constructor in the following manner:When creating a set using the Set constructor our newly created set object inherits from the
Set.prototype
. This has all sorts of auxiliary methods and properties. This allows you to easily do the following things:Example:
Browser compatibility:
All major browser now fully support sets except IE where some features are missing. For exact reference please refer to the mdn docs.
You can try Buckets, is a javascript data structure library and has everything you need to manipulate sets.