Everything you need to know about JavaScript Set

Everything you need to know about JavaScript Set

ยท

7 min read

JavaScript objects and arrays are the most used data structures act as collections of data. Until ES6 there were limited options with developers. But with ES6 we have got two new flexible and easy to use data structures, Map and Set .

In this article, we will learn about Set and we are going to make some salad(๐Ÿฅ—) too!

Set

A Set is a collection of unique(distinct) elements where each of the elements can be of any type. The Set is also an ordered collection of elements. It means the retrieval order of the elements will be the same as that of the insertion order.

The JavaScript Set behaves the same way as the mathematical set.

Create a Set,

const set = new Set();
console.log(set);

Output,

Set(0) {}

Initialize a Set and create,

const fruteSet = new Set(['๐Ÿ‰', '๐ŸŽ', '๐Ÿˆ', '๐Ÿ']);
console.log(fruteSet);

Output,

Set(4) {"๐Ÿ‰", "๐ŸŽ", "๐Ÿˆ", "๐Ÿ"}

Set methods - Let's make some Salad ๐Ÿฅ—!

Set has methods to add an element to it, delete elements from it, check if an element exists in it, and to clear it completely. Let us see it by making some salad!

Add vegetables

Use the add(element) method to add an element to the Set.

// Create a set - saladSet
const saladSet = new Set();

// Add some vegetables to it
saladSet.add('๐Ÿ…'); // tomato
saladSet.add('๐Ÿฅ‘'); // avocado
saladSet.add('๐Ÿฅ•'); // carrot
saladSet.add('๐Ÿฅ’'); // cucumber

console.log(saladSet);

Alright, we have added the vegetables. The output so far,

Set(4) {"๐Ÿ…", "๐Ÿฅ‘", "๐Ÿฅ•", "๐Ÿฅ’"}

Add another Cucumber - Can we?

I love cucumber! How about adding one more of it. Can I? Oh no, I can't. The Set is a collection of unique elements.

saladSet.add('๐Ÿฅ’');
console.log(saladSet);

Output is still as before, nothing got added to the saladSet.

Set(4) {"๐Ÿ…", "๐Ÿฅ‘", "๐Ÿฅ•", "๐Ÿฅ’"}

Does it have a Carrot(๐Ÿฅ•) or a Broccoli(๐Ÿฅฆ)?

Use the has(element) method to search an element in a Set.

// The salad has a ๐Ÿฅ•, so returns true
console.log('Does the Salad has Carrot?', saladSet.has('๐Ÿฅ•'));

// The salad doesn't have a ๐Ÿฅฆ, so returns false
console.log('Does the Salad has Broccoli?', saladSet.has('๐Ÿฅฆ'));

Lets remove the Avocado(๐Ÿฅ‘)

Use the delete(element) method to remove an element from a Set.

saladSet.delete('๐Ÿฅ‘');
console.log('I do not like ๐Ÿฅ‘, remove from the salad:', saladSet);

Now our salad set is,

I do not like ๐Ÿฅ‘, remove from the salad: Set(3) {"๐Ÿ…", "๐Ÿฅ•", "๐Ÿฅ’"}

Let's clean up, finish the salad!

Use the clear() method to remove all the elements from a Set.

saladSet.clear();
console.log('Finished it:', saladSet);

Output,

Finished it: Set(0) {}

Iteration with Set

The Set has a method called, values() which returns a SetIterator to get all the values.

// Create a Set
const houseNos = new Set([360, 567, 101]);

// Get the SetIterator using the `values()` method
console.log(houseNos.values());

Output,

SetIterator {360, 567, 101}

We can use forEach or for-of loop on this to retrieve the values.

Interesting fact: JavaScript emphasizes to make Set compatible with Map. That's why we find two Set methods, keys() and entries() like Map.

As Set doesn't have a key, the keys() method returns a SetIterator to retrieve values.

console.log(houseNos.keys());

Output,

SetIterator {360, 567, 101}

Try entries() now. For Map it returns the iterator to retrieve key-value pairs. There is no key for the Set. Hence the entries() method returns a SetIterator to retrieve the value-value pairs.

console.log(houseNos.entries());

Output,

SetIterator {360 => 360, 567 => 567, 101 => 101}

Let's Enumerate

We can enumerate over a Set using forEach and for-of loop.

houseNos.forEach((value) => {
   console.log(value);
});

Output,

360
567
101

With for-of,

for(const value of houseNos) {
   console.log(value);
 }

Set and object

A Set can have elements of any type, even objects.

// Create a person object
const person = {
   'name': 'Alex',
   'age': 32
 };

// Let us create a set and add the object to it
const pSet = new Set();
pSet.add(person);
console.log(pSet);

Output,

image.png

No surprise. The Set contains one element that is an object. Let us now, change a property of the object and add it to the set again.

// Change the name of the person
person.name = 'Bob';

// Add the person object to the set again
pSet.add(person);
console.log(pSet);

What do you think about the output? Two person objects or the one? Here is the output,

image.png

Set is the collection of unique elements. By changing the property of the object, we haven't changed the object itself. Hence Set will not allow duplicate elements.

Set and Array

An array, like a Set, allows adding and removing elements to it. But Set is different than array and it is not meant to replace array. Using Set as an add-on to array actually give more muscles.

The major difference between an array and Set is, array allows duplicate elements where Set is for distinct elements. Some of the Set operations(delete) are also faster than array operations(shift, splice).

The Set data structure is not a replacement of the array. Set along with array can solve interesting problems.

Convert Set to an array

In many situations, you may want to convert a Set to an array. In fact, it is very easy!

const arr = [...houseNos];
console.log(arr);

Output,

image.png

Unique values from an array using Set

The most common usage of the Set data structure is to get unique values from an array.

// Create a mixedFruit array with few duplicate fruits
const mixedFruit = ['๐Ÿ‰', '๐ŸŽ', '๐Ÿ‰', '๐Ÿˆ', '๐Ÿ', '๐ŸŽ', '๐Ÿˆ',];

// Pass the array to create a set of unique fruits
const mixedFruitSet = new Set(mixedFruit);

console.log(mixedFruitSet);

Output,

Set(4) {"๐Ÿ‰", "๐ŸŽ", "๐Ÿˆ", "๐Ÿ"}

Set Operations

It is very easy to perform the basic set operations like, union, intersection, diference, superset, subset etc with Set and array together. Let us take these two sets to perform these oprtations,

const first = new Set([1, 2, 3]);
const second = new Set([3, 4, 5]);

Union

Union-PixTeller.png

Union of the sets A and B, denoted A โˆช B, is the set of all items that is a member of A, or B, or both. For example. the union of {1, 2, 3} and {3, 4, 5} is the set {1, 2, 3, 4, 5}.

// Union
const union = new Set([...first, ...second]);
console.log('Union:', union);

Output,

Union: Set(5) {1, 2, 3, 4, 5}

Intersection

Intersection-PixTeller.png

Intersection of the sets A and B, denoted A โˆฉ B, is the set of all objects that are members of both A and B. For example, the intersection of {1, 2, 3} and {3, 4, 5} is the set {3}.

// Intersection
const intersection = new Set([...first].filter(elem => second.has(elem)));
console.log('Intersection:', intersection);

Output,

Intersection: Set(1) {3}

Difference

image.png

Set difference of U and A, denoted U \ A, is the set of all members of U that are not members of A. The set difference {1, 2, 3} \ {3, 4, 5} is {1, 2}, while conversely, the set difference {3, 4, 5} \ {1, 2, 3} is {4, 5}.

// Difference
const difference = new Set([...first].filter(elem => !second.has(elem)));

Output,

Difference: Set(2) {1, 2}

Superset

Subset-PixTeller.png

A set A is a subset of a set B if all elements of A are also elements of B; B is then a superset of A.

// Is a superset?
const isSuperset = (set, subset) => {
  for (let elem of subset) {
     if (!set.has(elem)) {
         return false;
     }
  }
  return true;
}
console.log('Is Superset?', isSuperset(first, second));

Output,

Is Superset? false

Here is some more information about Set vs Array:

Conclusion

Set is a great data structure to use as an add-on with JavaScript arrays. It doesn't have a huge advantage over array though. Use it when you need to maintain a distinct set of data to perform set operations like, union, intersection, difference etc.

Here is the GitHub repository to find all the source code used in this article(and in the previous article on Map). If you like, please show your support by giving it a star.

Know more about the Set data structure from here,

You may also like,


If it was useful to you, please Like/Share so that, it reaches others as well. Please hit the Subscribe button at the top of the page to get an email notification on my latest posts.

Follow me on twitter @tapasadhikary for more updates.

Did you find this article valuable?

Support Tapas Adhikary by becoming a sponsor. Any amount is appreciated!