What is set in JavaScript?
In JavaScript, a set is a data structure utilized for storing a collection of distinct values. Sets enable us to manage various types of data, but they inherently do not allow for duplicate values or items.
When a duplicate or identical value is present in a set, only the initial occurrence will be retained. In simpler terms, a set is a data structure that enables the storage of distinct values, ensuring that no element can appear more than once.
The set object in JavaScript is designed to hold elements that possess unique values. These values can be of any type, including both primitive values and references to objects.
Syntax:
new Set([iterable])
Parameter
iterable - This denotes an iterable entity whose components are to be incorporated into the newly created Set.
Points to remember
- A set object uses the concept of keys internally.
- A set object cannot contain the duplicate values.
- A set object iterates its elements in insertion order.
How to create a Set in JavaScript
In JavaScript, sets can be utilized to generate unique values. For instance, we can leverage a set to construct an identifier (ID).
Example:
const ids = new Set ();
To initiate the creation of a set, we must begin with the keywords new and set.
Set (0) {size: 0}
Additionally, we have the capability to initialize a set with values from an iterable by constructing a set. We can provide various iterables, including arrays, sets, or nodelists, to the set constructor.
Example:
To illustrate how we can assign values to a set, let us consider an example.
const ids = new Set ([2,4,5,6]);
console.log (ids);
Output:
Set(4) {2, 4, 5, 6}
Methods or Properties of a Set in JavaScript
In JavaScript, there exists a variety of methods and properties within the Set object that allow us to retrieve, insert, remove, and verify all elements contained in the set. Let’s explore these properties and methods comprehensively and examine their usage through practical examples involving a set.
Using set. add
The method set.add is utilized to append a new element with a designated value to the conclusion of the set object. In essence, it serves the purpose of incorporating additional values into the set.
Syntax
Set_name.add (element)
Example
const cars = new Set(['BMW', 'Mercedes',' Audi']);
cars.add('Porsche');
console.log(cars);
Output:
Set(4) { 'BMW', 'Mercedes', 'Audi', 'Porsche' }
Using set.delete
An item can be removed from a set utilizing the delete method. By employing set.delete, we are able to eliminate a particular element from the set instance.
Syntax:
Set1.delete(val);
Example:
const cars = new Set(['BMW', 'Mercedes',' Audi']);
cars.delete('Mercedes');
console.log(cars);
Output:
Set(2) { 'BMW', 'Audi' }
Using has method
The has method is utilized to verify whether a specific element exists within a set. It returns true if the specified element can be found within the set object.
Syntax:
Set_name.has (val);
Example:
let set1 = new Set();
set1.add(45);
set1.add(34);
set1.add(3);
console.log(set1.has(45));
console.log(set1.has(34));
console.log(set1.has(3));
Output:
true
true
true
Using set.values
The values method of the Set object is utilized to obtain the values contained within a set. This method yields an iterable, which can then be traversed using either a for loop or a for...of loop.
In straightforward terms, it provides the values from the collection while maintaining the original order in which they were inserted.
Syntax:
set1.values();
Example:
const vegetables = new Set([100,321, 234, 45, 76]);
for (const vegetable of vegetables. values()){
console.log(vegetable);
}
Output:
100
321
234
45
76
Using set. Clear
Utilizing the clear method allows us to remove all items present in the set. In straightforward terms, it eliminates every element from the set.
Syntax:
Set1. clear();
Example:
let set1 = new Set([11, 12, 13, 14, 15]);
console.log(set1);
set1.clear()
console.log(set1);
Output:
Set(5) { 11, 12, 13, 14, 15 }
Set(0) {}
Using set. entries
All elements within a set can be obtained by utilizing the entries method, which provides an iterable that allows for iteration through a for loop or a for-of loop.
Syntax:
Set_name.entries();
Example:
let set1 = new Set();
set1.add(50);
set1.add(40);
set1.add(30);
set1.add(20);
set1.add(10);
let getEntriesArry = set1.entries();
console.log(getEntriesArry.next().value);
console.log(getEntriesArry.next().value);
console.log(getEntriesArry.next().value);
Output:
[ 50, 50 ]
[ 40, 40 ]
[ 30, 30 ]
Advantages of sets in JavaScript
There are some benefits of using sets in JavaScript such as:
- By using sets, we can store unique values to avoid the duplication of the element in the present set.
- In JavaScript, element in a set are stored in such way that makes it efficient.
- There is no error of overflowing of the set because sets are dynamic.
- They provide fast and efficient operations for checking if an element is present in the set or not.
- We can implement the set using different data structure, such as HashSets and TreeSets each with its own advantages and their use cases.
- They can be used in a variety of applications, including algorithms, data analysis, and databases.
JavaScript Set Methods
Let us examine the compilation of JavaScript set methods along with their corresponding explanations.
| Methods | Description |
|---|---|
| add() | It adds the specified values to the Set object. |
| clear() | It removes all the elements from the Set object. |
| delete() | It deletes the specified element from the Set object. |
| entries() | It returns an object of Set iterator that contains an array of [value, value] for each element. |
| forEach() | It executes the specified function once for each value. |
| has() | It indicates whether the Set object contains the specified value element. |
| values() | It returns an object of Set iterator that contains the values for each element. |