Set is a new Object type introduced in ES6. The Set allows you to create a collection of unique values. Values stored in a set can be of any type - primitive or object.
Set is a collection of unique values.
You can also store NaN and undefined in a Set. Although in javascript, [NaN!==NaN], but a Set will equate it and store only unique values.
Creating a Set
Set is created using the new keyword. You can pass an iterable to the Set constructor and, it will copy the passed elements in the newly created Set.
let set = new Set();
// Set(0) {}
let set = new Set([1,2,1,2]);
// Set(2) {1, 2}
let set = new Set([NaN, undefined, Nan, undefined]);
// Set(2) {NaN, undefined}
.
Adding an element to a Set
To add a new element to a set, you can use set.add(value) method.
The add method add the passed value to the set and returns the set itself.
let set = new Set([1,2,3,4]);
set.add(5);
console.log(set);
// Set(5) {1, 2, 3, 4, 5}
let newSet = set.add(6);
console.log(newSet);
// Set(6) {1, 2, 3, 4, 5, 6}
.
Deleting an element from a Set
Set has a method set.delete(value) to delete the value passed to it from the set. It returns true if the set has the value passed to it prior to the call and false otherwise.
let set = new Set([1,2,3,4,5]);
let isDeleted = set.delete(5);
console.log(set);
// Set(4) {1, 2, 3, 4}
console.log(isDeleted);
// true
.
Checking if a value exists in a Set
To check if a value is present in a Set, we can use set.has(value) method. It returns true if the value is present in the set and false if it does not exist.
let set = new Set([1,2,3,4,5]);
let isPresent = set.has(3);
console.log(isPresent);
// true
.
Removing all elements from a Set
Set also provides a method set.clear() to delete all elements from the set.
let set = new Set([1,2,3,4,5]);
console.log(set);
// Set(5) {1, 2, 3, 4, 5}
set.clear();
console.log(set);
// Set(0) {}
.
Get count of elements in a Set
To get the count of element in the Set, we can use set.size property of the Set.
let set = new Set([1,2,3,4,5]);
console.log(set.size);
// 5
.
Summary
In this article we learned:
- Set is a collection of unique values.
- We can use the new keyword to create a new Set.
- We can add an element to a set using set.add(value).
- We can delete an element from a set using set.delete(value).
- We can check if a value exists in a set using set.has(value).
- We can remove all elements from a set using set.clear().
- We can get the count of elements in a set using the set.size property.
This article was first published on hackinbits.com
Top comments (0)