Set only contains unique values of any type, no same or duplicates are allowed in set. Set is object in javascript.
How to Create Set
Set accepts array as parameter.
Syntax
variable_name = new Set([]);
Example
<script>
const text = new Set(["hello","a","1",23]);
</script>
In above example, const text variable is declared and assigned a new Set.
With add() method
with add() method, single element or value can be added, to add multiple values in set loop is required.
<script>
const text = new Set();
text.add("world");
text.add("a");
text.add(1);
text.add("b");
text.add("hi");
</script>
Get size of Set
In javascript, size property is used to get the length or number of elements present in set.
<script>
const text = new Set();
text.add("a");
text.add("b");
text.add(c);
text.add("d");
text.add("e");
// Returns size of set
document.write(text.size);
</script>
Get elements of Set
for of loop is used in javascript to get elements of Set.
<script>
const text = new Set();
text.add("a");
text.add("b");
text.add(c);
text.add("d");
text.add("e");
for (const x of text) {
document.write(x);
}
</script>
Delete or Remove sets all element
clear() method of set is used to remove all elements of set at once.
<script>
const text = new Set();
text.add("a");
text.add("b");
text.add(c);
text.add("d");
text.add("e");
text.clear(); // Deletes all set elements
</script>
Delete value from set
delete() method is used to delete an element from set, this method accepts value as parameter to delete element or value.
<script>
const text = new Set();
text.add("a");
text.add("b");
text.add(c);
text.add("d");
text.add("e");
text.delete("c"); // Deletes value from set
</script>
Check value exist or not in set
To check given value is exists or not in Set, has() is used. It accepts a parameter to check value is present or not in given set.
<script>
const text = new Set();
text.add("a");
text.add("b");
text.add(c);
text.add("d");
text.add("e");
text.has("c"); // if exists, returns true
</script>
Set Methods
new Set() | Create a new set object |
add() | Add or insert new element. |
clear() | Remove all set element at once |
delete() | Delete given value from set |
has() | Checks value is present in set or not |
values() | Returns iterator object with set values |
keys() | Works same as values(), Returns iterator object with values in a set. |
entries() | Return [value, value] from set. |
forEach() | Calls the function for each element of set |