Sets are a data structure in JavaScript that allow you to store unique values of any type. In this blog, we will cover everything you need to know about sets in JavaScript, including their syntax, methods, and practical use cases.
Here is a table showing all the inbuilt methods of sets in JavaScript:
Method | Description |
---|---|
add() | Adds a new value to the set. |
clear() | Removes all values from the set. |
delete() | Removes a specific value from the set. |
entries() | Returns an iterator that contains the [value, value] pairs for each value in the set. |
forEach() | Executes a provided function once for each value in the set, in insertion order. |
has() | Returns a Boolean indicating whether the specified value is present in the set or not. |
keys() | Returns an iterator that contains the values for each value in the set. |
size | Returns the number of values in the set. |
values() | Returns an iterator that contains the values for each value in the set. |
You can create a set in JavaScript by using the built-in Set constructor. Here is an example:
const mySet = new Set();
This creates an empty set. You can also pass an iterable object, such as an array, into the constructor to create a set with initial values:
const mySet = new Set([1, 2, 3]);
You can add a value to a set using the add() method:
mySet.add(4);
You can remove a value from a set using the delete() method:
mySet.delete(3);
You can check the size of a set using the size property:
console.log(mySet.size); // Output: 3
You can check if a value exists in a set using the has() method:
console.log(mySet.has(2)); // Output: true console.log(mySet.has(5)); // Output: false
You can iterate over a set using the forEach() method:
mySet.forEach(value => console.log(value));
You can convert a set to an array using the spread operator:
const myArray = [...mySet];
Here's an example of how to use the entries() method to iterate over the [value, value] pairs for each value in a set:
const set = new Set(['apple', 'banana', 'cherry']); const iterator = set.entries(); console.log(iterator.next().value); // Output: ['apple', 'apple'] console.log(iterator.next().value); // Output: ['banana', 'banana'] console.log(iterator.next().value); // Output: ['cherry', 'cherry']
In this example, we create a set set with the values 'apple', 'banana', and 'cherry'. We then use the entries() method to create an iterator that contains the [value, value] pairs for each value in the set.
We use the next() method on the iterator to iterate over each pair. The next() method returns an object with a value property that contains the next [value, value] pair in the iteration, as well as a done property that indicates whether the end of the iteration has been reached. Note that since sets only contain unique values, the entries() method returns pairs with the same value for both the key and the value. However, the entries() method is still useful for iterating over the values in a set in a consistent order.
Here's an example of how to use the keys() method to iterate over the values in a set:
const set = new Set(['apple', 'banana', 'cherry']); const iterator = set.keys(); console.log(iterator.next().value); // Output: 'apple' console.log(iterator.next().value); // Output: 'banana' console.log(iterator.next().value); // Output: 'cherry'
In this example, we create a set set with the values 'apple', 'banana', and 'cherry'. We then use the keys() method to create an iterator that contains the keys (i.e., the values themselves) for each value in the set.
We use the next() method on the iterator to iterate over each key. The next() method returns an object with a value property that contains the next key in the iteration, as well as a done property that indicates whether the end of the iteration has been reached.Note that the keys() method is equivalent to the values() method, since sets only contain unique values. However, the keys() method is still useful for iterating over the values in a set in a consistent order.
In addition to these methods, there are also some static methods for sets:
Method | Description |
---|---|
Set() | Creates a new set. |
from() | Creates a new set from an iterable object. |
isSet() | Returns true if the provided value is a set; otherwise false. |
of() | Creates a new set with a variable number of arguments. |
These inbuilt methods and static methods make working with sets in JavaScript easier and more efficient.
Here's an example of how to use the from() method to create a new set from an array:
const arr = [1, 2, 3, 3, 4, 5, 5]; const set = new Set.from(arr); console.log(set); // Output: Set {1, 2, 3, 4, 5}
In this example, we create an array arr with some duplicate values. We then use the from() method to create a new set set from the array. The resulting set contains only the unique values from the original array, since sets can only contain unique values.
We can also use the from() method to create a new set from a string:
const str = 'hello'; const set = new Set.from(str); console.log(set); // Output: Set {'h', 'e', 'l', 'o'}
In this example, we create a string str and use the from() method to create a new set set from the string. The resulting set contains each character in the string as a separate value.Note that the from() method can also be used with other iterable objects, such as maps or arrays of arrays. This makes it a very versatile method for creating sets from existing data structures.
Here's an example of how to use the isSet() method to check if a provided value is a set
const set = new Set([1, 2, 3]); console.log(Set.isSet(set)); // Output: true const arr = [1, 2, 3]; console.log(Set.isSet(arr)); // Output: false
In this example, we create a set set and use the isSet() method to check if it is a set. Since set is a set, the method returns true. We then create an array arr and use the isSet() method to check if it is a set. Since arr is not a set, the method returns false.
The isSet() method can be useful in situations where you need to check the type of a value before performing certain operations on it.
Here's an example of how to use the of() method to create a new set with a variable number of arguments:
const set = new Set.of(1, 2, 3); console.log(set); // Output: Set {1, 2, 3}
In this example, we use the of() method to create a new set set with the values 1, 2, and 3. The resulting set contains these values as separate values.
We can also use the of() method to create a set with a single value:
const set = new Set.of(1); console.log(set); // Output: Set {1}
In this example, we create a new set set with the value 1. The resulting set contains this value as a single value. Note that the of() method is a static method, which means that it is called on the Set constructor rather than on an instance of the Set class. This allows us to create a new set without having to first create an empty set and then add values to it.
Here is the real time example for unique tag widget for website or blog.
class TagsInput { constructor() { this.tags = new Set(); } addTag(newTag) { this.tags.add(newTag); console.log(this.tags); } } const input = new TagsInput(); input.addTag("Ram"); input.addTag("Sam"); input.addTag("Ram"); input.addTag("Ravi");
Sets are useful in a variety of situations, such as:
Removing duplicates from an array
Checking if an array contains a specific value
Tracking unique user IDs in an application
In this blog, we covered the basics of sets in JavaScript, including their syntax, methods, and practical use cases. By using sets, you can easily manage collections of unique values in your code.
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions