JavaScript — How to use the Set object

JavaScript has an object called Set which will store any type with unique values — this can be a primitive value type (e.g. string, number, boolean, null, undefined, symbol) or even an object reference.

//create a new Set
var setA = new Set();
//use .add() to add types to the set
setA.add(6); // Set is [6]
setA.add(9); // Set is [6,9]

//or create a Set by passing it an iterable object
var setA = new Set([6,9]); // Set is [6,9]

Because a value in a Set may only occur once, it will eliminate duplicates when you add them.

//Eliminates duplicate values on creation
var setB = new Set([6,7,8,9,6,7]); // Set is [6,7,8,9]

//Doesn't add new values if they already exist in the set
var setB = new Set();
setB.add(6)// Set is [6]
setB.add(7)// Set is [6,7]
setB.add(8)// Set is [6,7,8]
setB.add(6)// Set is [6,7,8]
setB.add(9)// Set is [6,7,8,9]
setB.add(7)// Set is [6,7,8,9]

Use the .has() method to check if a value is in the set. It will return a boolean of True or False depending on if it finds the value.

var setA = new Set([6,9,3,5,8]);
setA.has(5); // true
setA.has(2); // false

The .delete() method will remove a value from the set. It will return a boolean value if it found the value in the set.

var setA = new Set([6,9,3,5,8]);
setA.has(5); // true
setA.delete(5); // returns true
setA.has(5); // false -- Set is now [6,9,3,8]
setA.delete(5); // returns false

You can also remove ALL the values in the set with the .clear() method.

var setA = new Set([6,9,3,5,8]);
setA.has(5); // true

A Set does not have a Length property but it does has a Size which will tell you how many values are stored in the Set.

var setA = new Set([6,9,3,5,8]);
setA.size; // return 5
setA.length; // returns undefined

To keep the Set similar to the Map object, values are stored as a key/value pair where the key is the same as the value. You can retrieve all the values in a Set using the .entries() method. This will return an Iterator of all entries in a format of [value, value].

var setA = new Set([6,9,3,5,8]);
var myEntries = setA.entries();

You can also just get the keys or values for a Set using the .keys() or .values() methods, respectively. Both return a new Iterator object. Since the value is used as the key in a Set, both methods ultimately return the same result.

var setA = new Set([6,9,3,5,8]);

var setKeys = setA.keys();
// or
var setValues = setA.values();

Because a Set is an iterable object, you can use the .forEach() method to loop over the values in a Set. You can pass a call back function in as a parameter which will get called once for each value in the set. It also has an option argument which can be passed that will be used for the this value for each callback.

var setA = new Set([6,9,3,5,8]);

setA.forEach(function writeValue(value) {

// 6
// 9
// 3
// 5
// 8

// example passing 'a' as the thisArg to the forEach
setA.forEach(function writeValue(value) {
     console.log(value + '---'+ this );
}, 'a');

// 6---a
// 9---a
// 3---a
// 5---a
// 8---a

If you just want to iterate over the values in a Set, you also have the option of using a For loop.

var setA = new Set([6,9,3,5,8]);

for (let item of setA) {
// or 
for (let item of setA.values()) {

// both output
// 6
// 9
// 3
// 5
// 8

You can easily convert from a Set to an array using Array.from() method.

var setA = new Set([6,9,3,5,8]);

var array1 = Array.from(setA); // [6, 9, 3, 5, 8]

//you can also use the Spread Syntax to create the Array of Values
var array2 = [...setA]; // [6, 9, 3, 5, 8]

One neat trick you can use Set for is to de-dupe an Array.

var array1 = [6,9,3,5,8,9,4,2,1,2,2]

var setB = new Set(array1);

var array2 = [...setB] //[6, 9, 3, 5, 8, 4, 2, 1]

// or you can simplify things like so
var array3 = [ Set([6,9,3,5,8,9,4,2,1,2,2])]; 
//[6, 9, 3, 5, 8, 4, 2, 1]

Another is to use Set as a way to break a string apart to it’s individual unique letters.

var myString = 'Hello';

var charSet = new Set(myString); // ["H", "e", "l", "o"]
charSet.size; //4

//just keep in mind that case sensitivity counts
var myString2 = 'HeLlo';

var charSet2 = new Set(myString2); // ["H", "e", "L", "l", "o"]
charSet2.size; //5

There are a couple things to keep in mind. A set can only contain unique values. When you interate over a Set object, it returns the values in insertion order (how they go in is how they come out).

Objects can be a bit confusing at first compared to primitive types. For instance:

var obj = {'a': 1, 'b':2}
var obj2 = {'a': 1, 'b':2}
var mySet = [{'a': 1, 'b':2}, obj, obj2]

// mySet now contains
// [{'a': 1, 'b':2}, {'a': 1, 'b':2}, {'a': 1, 'b':2}]