What are the sets? How to use them in JavaScript? And what methods does provide to solve problems? Let’s find out the answers to all the queries in this tutorial.
Sets
As the name indicates, a set is a collection of unique elements. It doesn’t store the repeated values. Sets in JavaScript will store the elements in the insertion order. So, they are ordered in JavaScript. And it will store primitive data types or objects. Let’s see the syntax of the sets in JavaScript.
Properties and Methods
Sets have different properties and methods that help us work with them to solve different problems. The properties and methods are as simple as creating them. You can easily get the functionality of the methods with their names themselves. Let’s see them one by one.
size
The property size returns the number of elements present in the set.
add
The method add is used to add a new element to the set. If the new element is already present in the set, then it won’t add it.
has
The method has takes one argument and returns true if the element is present in the set else it returns false.
delete
As you expect the method delete takes an argument and deletes it from the set. It doesn’t throw any error even if the given argument is not present in the set.
entries
The method entries returns an iterator containing arrays of key-value pairs in the insertion order. Here, key and value are the same.
keys
The method keys returns an iterator of set elements in the insertion order.
values
The method values returns an iterator of set elements in the insertion order similar to the method keys.
clear
The method clear removes all the elements from the set.
forEach
The method forEach is used to iterate over the set and get all the elements one by one from it.
Miscellaneous
Let’s see a simple application of sets with a program. Given an array remove all the duplicate values from it. To solve the problem, we can make use of the set property. Let’s see the step to solve it.
Initialize an array with dummy data. Initialize an empty set. Iterate over the array of elements. Add every element to the set. It will remove duplicate elements automatically. Initialize an empty array. Iterate over the set and add every element to the new array. Print the new array.
I hope you can solve it yourself. If you find it difficult to code, have a look at the solution below.
Conclusion
Now, you have all the knowledge that need to work with sets in JavaScript. You can use them in your next project. Go ahead and make use of every bit of it. Happy Coding 👨💻