Junior
What is the purpose of Set in JavaScript?
sobes.tech AI
Answer from AI
Set is used to store a collection of unique values of any type. This means that there can be no duplicates in a Set.
Main purposes of using Set:
- Removing duplicates: An efficient way to get unique elements from an array or other iterable structure.
- Existence check: Fast check if an element exists in the collection, thanks to an optimized data structure.
- Managing unique elements: Convenient for tasks where the uniqueness of each element is important.
Examples of usage:
- Getting a list of unique online users.
- Storing unique tags for an article.
- Implementing algorithms that require working with sets (intersection, union).
Set supports methods for working with the collection, such as add(), delete(), has(), clear(), and can be iterated with for...of or the forEach() method.
const mySet = new Set([1, 2, 2, 3, 'a', 'a']);
console.log(mySet); // Set { 1, 2, 3, 'a' }
console.log(mySet.has(2)); // true
console.log(mySet.has('b')); // false
mySet.add(4);
console.log(mySet); // Set { 1, 2, 3, 'a', 4 }
mySet.delete('a');
console.log(mySet); // Set { 1, 2, 3, 4 }
for (const item of mySet) {
console.log(item);
}
// Output:
// 1
// 2
// 3
// 4