Loading...

Sets in JavaScript

Sets in JavaScript

The way of structuring the data plays an important role in our ability to perform different operations on data or to solve problems that are related to the data. JavaScript has some basic data types such as arrays, objects, strings, maps, sets, etc. Let us discuss the data type sets in this article.

What are sets in JavaScript?

Sets are the collection of values. The values of the set can occur only once. We can loop over the elements in a set. We can store any type of value whether primitive(strings, numbers, booleans) or object (object literals, arrays) in a set. 

A set in JavaScript is similar to that of sets in mathematics. Each value in a set is checked for equality as values in a set should be unique. As each of the values in a set is unique, the length of the set will not change on adding some of the existing values. Sets are closely related to arrays but when we use an array our focus is generally on the individual items in the array. When dealing with a set, we usually deal with the set as a whole.

Syntax:

new Set([value]);

Parameter: 

value – It is an object which is iterable and its elements are added to the new set created. When null is passed or the parameter is not specified inside the new set, the new set created is empty.

Returns: It returns a new set object.

Creating a new set in JavaScript

We can create a new set using the new set() constructor in JavaScript. The set object is capable of storing unique values of any datatype. Let us take an example for a better understanding of the concept.

const set1 = new Set([2, 4, 5, 6, 23, 43, 64,1, 21]); 
console.log(set1);

You will get the output as shown below:

set(9) { 2, 4, 5, 6, 23, 43, 64,1, 21}

We can also create a set that includes elements from different data types.

const set2 = new Set([11, 23, "java", [23, 43, 64,1, 21]]);
console.log(set2);

You will get the output as shown below:

set(4) {11, 23, "java", [23, 43, 64,1, 21]}

When we try to create a set that contains repeating elements, it returns a unique set that contains no duplicate elements.

const set3 = new Set([23, 43, 64,1, 21, 1, 1, 1, 64, 43, 43]);
console.log(set3);

You will get the output as shown below:

set(5) {23, 43, 64,1, 21}

An empty set is created when we do not specify anything in the parameter.

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

You will get the output as shown below:

Set(0) {}

How to add a new element to the existing set?

You can use the add() method to add a new element to the Set object in JavaScript. The add() method accepts the value of the element that needs to be added to the set object as a parameter and returns a new Set object with the added value. Let us take an example for a better understanding of the concept.

const set1 = new Set();
set1.add("Welcome");
set1.add("to");
set1.add("Codedamn");
console.log(set1);

You will get the output as shown below. 

Set(3) { 'Welcome', 'to', 'Codedamn' }

We can directly pass a value or a variable as a parameter as shown below.

const set1 = new Set();
// Adding value to a Set object
set1.add("Welcome");
const var1 = "to";
const var2 = "Codedamn";
// Adding variable to a Set object
set1.add(var1);
set1.add(var2);
console.log(set1);

You will get the output as shown below.

Set(3) { 'Welcome', 'to', 'Codedamn' }

We can also add multiple elements in a single chain using the add() method.

const set1 = new Set();
set1.add(11).add(26).add(34);
console.log(set1);

Output:

Set(3) { 11, 26, 34 }

Removing elements from a set

We can delete a specific element from a set using the delete() method. After giving the element that we need to delete, the method checks for that particular element in the set and if the element is found, it returns true else it returns false.

const setObj = new Set([14, 22, 3, 41, 53]);
console.log("Original set:");
console.log(setObj);
setObj.delete(53);
console.log("Set after deleting 53");
console.log(setObj);

You will get the output as shown below

Initial Set:
Set(5) { 14, 22, 3, 41, 53 }
Set after deleting 53
Set(4) { 14, 22, 3, 41 }

We can delete all the elements in the set using the clear() method

const set1 = new Set([14, 22, 3, 41, 53]);
console.log(set1);
set1.clear();
console.log(set1);

Output:

Set(5) { 14, 22, 3, 41, 53 }
Set(0) {}

Checking for an element in the set

We can check if the element is present in the given set or not using the has() method. This method checks for the presence of a given element in the set by taking the value as a parameter. If the element is present in the set, it returns true, otherwise, it returns false. Let us take an example for a better understanding of the concept.

const set1 = new Set(["Welcome", "to", "Codedamn"]);
console.log(set1.has("to"));
console.log(set1.has("monkey"));

Output:

true
false

Entries() method

This method returns a new iterator object which contains an array [value, value] for each element in the set.

const set1 = new Set();
set1.add(2);
set1.add('two');
const iterator1 = set1.entries();
for (const entry of iterator1) {
  console.log(entry);
  // expected output: [2, 2]
  // expected output: ["two", "two"]
}

Output:

[2, 2] 
['two', 'two']

Values() method

This method returns an object that contains all the values in the given set in insertion order. The key() method also works in the same manner as that of the values() method.

const set1 = new Set([1, 2, 3, 4, 5]);
const iterator1 = set1.values();
for (let value of iterator1) {
console.log(value);
}

Output:

1
2
3
4
5

Let us now look at some more methods of sets in brief.

Set.prototype.size

It is an instance property of sets rather than a method. It returns the number of values in the given set.

Set.prototype[@@iterator]()

It returns a new object that renders the values in insertion order for each element in the Set.

subSet() 

It returns true if a set is a subset of another given set otherwise it returns false.

Conclusion

This was about sets in JavaScript. Check out our free courses on JavaScript on Codedamn.

Sharing is caring

Did you like what Agam singh, Aman Ahmed Siddiqui, Aman Chopra, Aman, Amol Shelke, Anas Khan, Anirudh Panda, Ankur Balwada, Anshul Soni, Arif Shaikh, wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far