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
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 the ES6
built in set constructor in the following manner:
const set = new Set([1, 2, 3, 4, 5]);
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:
const set = new Set([1, 2, 3, 4, 5]);
// checkout the size of the set
console.log('size is: ' + set.size);
// has method returns a boolean, true if the item is in the set
console.log(set.has(1));
// add a number
set.add(6);
// delete a number
set.delete(1);
// iterate over each element using a callback
set.forEach((el) => {
console.log(el);
});
// remove all the entries from the set
set.clear();
All major browser now fully support sets except IE where some features are missing. For exact reference please refer to the mdn docs.