Updated March 27, 2023
Introduction to Javascript Set Class
Let us see the pure definition of Set, it is a well-defined collection of recognizably different objects, considered as an object. For example, 4, 3, 9, 6 are distinct objects when considered separately but when considered as a set, they form a set of size 4 written as {4, 3, 9, 6}.
In computer language, Sets are an abstract data type of new object with ES6 i.e. ECMAScript 6 is the current standard of javascript since 2015 which allows to create collections of unique values. These values can be primitives like strings, integers or complex objects like object literals or arrays. Sets in ES6 are ordered and considered as a keyed collection that uses keys and can be iterated in the insertion order.
Syntax
The syntax for creation of new Set.
Set had a built-in constructor:
var set_name = new Set();
var set_name = new Set([set of values separated with comma]);
Initializing a set:
var set1 = new Set();
var set2 = new Set([4,3,6]);
As set receives iterable object as its input parameter, we can construct set from the array which would not include duplicates.
var set2 = new Set([4,3,6]); returns {4, 3, 6}
var arr1 = Array.from(set2); returns [4, 3, 6]
Set does not support accessing an element by index randomly i.e set2[0] will return undefined unlike array which would return 4
Example:
var set2 = new Set([4,3,6]);
console.log(set2[0]);
var set3 = new Set([3, 2, 1]);
var arr1 = Array.from (set3);
console.log(arr1);
Output:
If we don’t specify the iterable data to a set, it will return null, set being empty. There are some methods used in set collection. They are applied on set.
- add
- delete
- size
- clear
- has
- .forEach
1. Set.add(value) returns set itself with added values. Repeated calls for same value won’t harm the set as it takes only unique values
2. Set.delete(value) returns Boolean values true or false and removes the value from the set.
3. Set.size is the size of the elements in a set.
4. Set.clear() removes the iterable data from the set.
5. Set.has(value) checks for the specified value in the set and returns true if the set consists of the value specified else returns false.
6. .forEach() is a loop used to iterate the set and print the values.
Examples of JavaScript Set Class
Consider an example which shows all the methods,
Example #1
Code:
let students = new Set();
students.add('Rohan');
students.add('Srikanth');
students.add('Lekha');
console.log(students.size);
students.add('Reshma');
console.log(students.size);
console.log(students.delete('Lekha'));
console.log(students.has('Rohan'));
students.delete('Rohan');
console.log(students.has('Rohan'));
console.log(students.size);
students.forEach(student => {
console.log(`Hi ${student}`)
});
Output:
Here, students are a new set of collections of student’s names, We added ‘Rohan’, ‘Srikanth’, ‘Lekha’ using .add() method and checked for the size of the set. Performed a .delete() method on the set to remove ‘Lekha’ which returned true as the iterable was present and deletion was successful. Likewise, we checked for .has() method which returns a Boolean value.
.forEach() iterates the set and returns each value by looping the set.
Example #2
Removing duplicate elements from an array: As said, set only takes unique values/ elements. Let us consider a set of elements having duplicate elements but can remove these duplicates.
Code:
const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]
console.log([...new Set(numbers)])
Output:
Example #3
Relation with strings: Using the set class, we can be able to find the size of the string. Let us consider string ‘Canada’ and pass this string to set.
Code:
let text = 'Europe';
var mySet = new Set(text // Set ['E', 'u', 'r', 'o', 'p', 'e']
console.log(mySet.size);
Output:
Text ‘Europe’ is passed to mySet which in turn converts the string into a set of keys.
Let us see some of the basic set operations such as superset, subset, union, intersection, and difference.
- superSet returns true if set A is superSet of set B.
- subSet returns true if set A is subSet of set B i.e all the elements of set A are present in set B.
- union returns true if set consists of a combination of set A and set B.
- intersection returns true if a set consists of elements that are both presents in set A and set B.
- difference returns true if the difference if set A and set B if it contains a set of elements that are present in set A and not set B.
Example #4
Example for subset
Code:
Set.prototype.subSet = function(exampleSet)
{
if(this.size > exampleSet.size)
return false;
else
{
for(var element of this)
{
if(!exampleSet.has(element))
return false;
}
return true;
}
}
var setA = new Set([1,2,3]);
var setB = new Set([4,6,3,2,1]);
console.log(setA.subSet(setB));
Output:
As set B consists of elements of set A, subSet returns true.
Weak Set
In a set, elements are not garbage collected whereas, in a weak set, all the elements are garbage collected. Each key of the weak set is an object. The weak set is garbage collected when the reference for the object is lost. Differences between the normal set and weak set are, we cannot iterate the weak set whereas, in a normal set, it can be iterated. All the elements of a weak set can be cleared whereas, in a normal set, elements can be cleared. Size of the normal set can be checked whereas for the weak set, size can not be checked. Weak set only has 3 methods, add(), has() and delete().
Comparison Between Set and an Array
Set contains only distinct elements and basic operations like union(), difference(), intersect(), subset(), etc are implemented based on built-in operators whereas array is meant for ordered elements with quick access and modifications like adding and removing elements.
In general, set are not that advantageous than array except when the user wants to maintain distinct data with the basic set of operations without directly accessing the element, else array can be considered as less work is needed to fetch the elements. Hence, we can conclude this article by saying sets should only be used while working with unique elements in the dataset. The new ES6 class allows set to accept only distinct objects, to remove an element from a set, delete method can be used whereas, in the array, we have to iterate using a loop and then remove using splice and also can convert set to an array using the spread operator.
Recommended Articles
This is a guide to JavaScript Set Class. Here we discuss the basic concept, examples, weak set, and comparison between set and an array. You may also have a look at the following articles to learn more –